#!/bin/bash -e

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

if [ ${0:0:2} == "./" ];then
    . ../data/functions
else
    . /usr/share/separator/functions
fi

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

$PROG install and setup system to <root> with config into <workdir>

Valid options are:
  -h, --help		display help screen
  -v, --version		display version information
  -r, --root=<path> 	path to root directory
  -c, --class=<WORD>	system class (live,vserver...)
  -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:,r:,c:,v,h,k: -l aptconf:,root:,class:,version,help,component: -- "$@"` || exit 1
eval set -- "$TEMP"

workdir=
deps_file=
langs=
COMPONENT=live.cnf
while :; do
	case "$1" in
		-h|--help) print_usage 0
		    ;;
		-r|--root)
			shift
			ROOT="$1"
		    ;;
		-k|--component)
			shift
			COMPONENT="$1"
		    ;;
		-c|--class)
			shift
			CLASS="$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

. "$PROFILE/config"
. $WORKDIR/profile/$COMPONENT || Fatal "File $WORKDIR/profile/$COMPONENT not found"


[ ! -z "$ROOT" ] || ROOT=`getroot $TMPDIR $OUT`
[ ! -z "$IDENT" ] || IDENT="packages"
IMG=$WORKDIR/tmp/$OUT.img

Info "removing old..."
[ ! -d $ROOT ] || for i in `ls -1A $ROOT`;do rm -Rf $ROOT/$i;done
Info "adding new ..."
mkdir -p $ROOT
ROOT=`realpath $ROOT`
init_root $ROOT "$LANGS"
[ -z "$CLASS" ] || postinstall_root $CLASS $ROOT
postinstall_local_root $WORKDIR $ROOT
install_packages $TMPDIR/$IDENT.packages $ROOT || exit 1
[ -z "$CLASS" ] || postinstall $CLASS $ROOT
postinstall_local $WORKDIR $ROOT
