#!/bin/sh
EEXIT=""

die() {
    echo $1
    if [ -n "$TMPDIR" -a -e "$TMPDIR" ]; then
        rm -rf $TMPDIR
    fi
    exit 1
}

if [ -z "$1" ]; then
    echo "Pass path to initrd"
    EEXIT=1
fi
if [ -z "$2" ]; then
    echo "Pass path to rootfs.img"
    EEXIT=1
fi
if [ -z "$3" ]; then
    echo "Pass name of new initrd"
    EEXIT=1
fi
if [ -n "$EEXIT" ]; then
    exit $EEXIT
fi

TMPDIR=$(mktemp -d)
[ -z "$TMPDIR" ] && die "mktemp failed"
mkdir $TMPDIR/LiveOS/ || die "mkdir LiveOS failed"
cp $2 $TMPDIR/LiveOS/rootfs.img || die "cp $2 failed"
if [ -e squashfs.img ]; then
    die "./squashfs.img cannot already exist"
fi
echo "Creating squashfs.img"
mksquashfs $TMPDIR ./squashfs.img -comp xz || die "mksquashfs failed"
echo "Creating $3"
(( echo "squashfs.img" | cpio -H newc --quiet -L -o ) | pigz -9 | cat $1 - > $3) || die "$3 creation failed"
rm ./squashfs.img
rm -rf $TMPDIR

echo "PXE APPEND should look like:"
echo "APPEND initrd=path/to/$3 root=live:/squashfs.img rd.live.image"
exit 0
