#!/bin/sh -e

PROG="${0##*/}"

if [ "$0" = ./$PROG ]; then
    . ../data/functions
    SCRIPTDIR=.
else
    . /usr/share/separator/functions
fi

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [options] <workdir>

$PROG create compressed image for livecd

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
  -s, --squashfs create squashfs instead of cloop
  -k, --component=<file> configuration file for component (live.cnf default)

Report bugs to <rider@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}


#parse command line options
TEMP=`getopt -n $PROG -o a:,v,h,s,k -l aptconf:,version,help,squashfs,component: -- "$@"` || exit 1
eval set -- "$TEMP"

workdir=
deps_file=
langs=
SQUASHFS=
COMPONENT=live.cnf
while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-w|--workdir)
			shift
			workdir="$1"
		    ;;
		-k|--component)
			shift
			COMPONENT="$1"
		    ;;
		-s|--squashfs)
			SQUASHFS=1
		    ;;
		-v|--version) print_version; exit 0
		    ;;
		--) shift; break
		   ;;
		*) "unrecognized option: $1"
		    exit 1
			;;
	esac
	shift
done

WORKDIR=$@

[ -z "$WORKDIR" -o "`id -u`" != "0" ] && print_usage 0
WORKDIR=`realpath $WORKDIR`
APTBOX="$WORKDIR/aptbox"
PROFILE="$WORKDIR/profile"
LISTDIR="$PROFILE/packages"
TMPDIR=$WORKDIR/tmp
OUTDIR=$WORKDIR/out

ROOT="${WORKDIR}/root"
IMG=$WORKDIR/tmp/altlinux.img

. $WORKDIR/profile/config || exit 1

. $WORKDIR/profile/$COMPONENT || exit 1

ROOT="${TMPDIR}/$OUT.root"
IMG=$WORKDIR/tmp/$OUT.img

mkdir -p $OUTDIR
if [ -z "$SQUASHFS" ];then
    size=$((`du -ks $ROOT|cut -f1`+8000))
    echo "size: $size";
    e2fsimage -f $IMG -d $ROOT -s $size -p
    /sbin/fsck.ext3 -f -y $IMG ||:
    create_compressed_fs $IMG 131072 > $OUTDIR/$OUT
else
    [ -f $OUTDIR/$OUT ] && rm -f $OUTDIR/$OUT
    for i in `find $ROOT/ -type l`;do 
	lnk=`readlink $i`; 
	if [ ${lnk:0:1} == "/" ];then 
	    newlnk=${lnk##$ROOT};
	    rm -f $i;
	    ln -s $newlnk $i;
	fi;
    done
    /sbin/mksquashfs $ROOT $OUTDIR/$OUT 
fi

postinstall image $CLASS $classdir/$CLASS/postimage.d
