#!/usr/bin/sh

error() {
    cat <<EOF;
usage: mdkinst_stage2_tool [--clean] [--compress | --uncompress] <stage2 dir> [<compressed file>]
EOF
    exit 1
}

if [ "$1" = "--clean" ]; then
    CLEAN=1
    shift
fi

[ $# = 2 -o $# = 3 ] || error

if [ "$1" = "--compress" -o "$1" == "--uncompress" ]; then
    ACTION=$1
    shift
    STAGE2_DIR="$1"
    shift
    LIVE_DIR="$STAGE2_DIR/live"
    if [ -n "$1" ]; then
	COMPRESSED_IMAGE=$1
	shift
    else
	COMPRESSED_IMAGE="$STAGE2_DIR/mdkinst.sqfs"
    fi
else
    error
fi

if [ $ACTION = "--compress" ]; then
    which mksquashfs >/dev/null 2>/dev/null || { echo "missing command mksquashfs (from squashfs-tools)"; exit 1; }

    [ -d "$LIVE_DIR" ] || error
    echo "Creating $COMPRESSED_IMAGE from $LIVE_DIR"
    rm -f $STAGE2_DIR/.room
    if ! mksquashfs $LIVE_DIR $COMPRESSED_IMAGE -all-root -noappend >/dev/null; then
	echo "mksquashfs failed"
	exit 1
    fi
    chmod 755 $COMPRESSED_IMAGE
    echo foo > $STAGE2_DIR/.room
    if [ -s $STAGE2_DIR/.room ]; then
	rm -f $STAGE2_DIR/.room
	[ -n "$CLEAN" ] && rm -rf $LIVE_DIR 
    else
	echo "not enough space"
	rm -f $COMPRESSED_IMAGE
	exit 1
    fi
else
    which unsquashfs >/dev/null 2>/dev/null || { echo "missing command unsquashfs (from squashfs-tools)"; exit 1; }

    [ -f "$COMPRESSED_IMAGE" ] || error
    echo "Creating $LIVE_DIR from $COMPRESSED_IMAGE"

    if [ $EUID != "0" ]; then
	SUDO="sudo"
	PATH="/sbin:/usr/sbin:$PATH"
    fi

    unsquashfs -dest $LIVE_DIR $COMPRESSED_IMAGE || { rm -rf $LIVE_DIR; exit 1; }

    [ -n "$CLEAN" ] && rm -f $COMPRESSED_IMAGE
fi

exit 0
