#!/bin/sh -e
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*-
#  $Id: initchroot,v 1.2 2005/05/27 13:55:23 legion Exp $ 

PROG="${0##*/}"
target='i586'
apt_config=
quiet=1
chroot_cleanup=

Fatal() {
    printf %s\\n "$PROG: $*" >&2
    exit 1
}

Message() {
    [ -z "$quiet" ] || return 0
    printf %s\\n "$*"
}

Usage() {
    [ "$1" = 0 ] || exec >&2
    cat <<EOF
Usage: $PROG [options] <path-to-workdir> <package>...

<path-to-workdir> must be valid writable directory.

Valid options are:
  --apt-congig=FILE         path to custom apt.conf file;
  -t, --target=ARCH         init architecture;
  -c, --chroot-cleanup      remove old chroot;
  -q, --quiet               try to be more quiet;
  -h, --help                show this text.
EOF
    [ -n "$1" ] && exit "$1" || exit
}

TEMP=`getopt -n $PROG -o a:,c,h,q,t: -l apt-config:,chroot-cleanup,help,quiet,target: -- "$@"` || Usage
eval set -- "$TEMP"

while :; do
    case "$1" in
	-a|--apt-config) shift
	    [ -z "$1" ] || { [ ! -r "$1" ] || apt_config="$(realpath "$1")"; }
	    ;;
	-c|--chroot-cleanup) chroot_cleanup=1
	    ;;
	-q|--quiet) quiet="$1"
	    ;;
	-h|--help) Usage 0
	    ;;
	-t| --target) shift; target="$1"
	    ;;
	--) shift; break
	    ;;
	*) Fatal "unrecognized option: $1"
	    ;;
    esac
    shift
done

[ "$#" -ge 1 ] || Usage 1

work_dir="$1" && shift
requires="$@"

[ -z "$quiet" ] || exec >/dev/null
[ -z "$chroot_cleanup" ] || hsh --cleanup-only ${quiet:+--quiet} -- "$work_dir" 

# Make init root
hsh \
    ${quiet:+--quiet} \
    ${target:+--target=$target} \
    ${apt_config:+--apt-config="$apt_config"} \
    --no-cache --no-contents-indices --without-stuff --excludedocs --initroot-only \
    -- "$work_dir" || Fatal "Cant make initroot"

[ -n "$requires" ] || exit 0

Message "Install check requires: $requires"
hsh-install "$work_dir" ${quiet:+--quiet} --excludedocs $requires || Fatal "Cant install requires: $requires"
