#! /bin/bash

function showHelp()
{
    echo "Usage: start-build [-s slave] [-e] <arch> <url> <md5sum> <gpg-key#>"
    exit 0
}

function exitFunc()
{
    set +e
    test   -z "$slave_started" || $DJINNI -q stop_bslave "$slave"
    test ! -f "$slave_lock"    || rm -f  "$slave_lock"
    test ! -d "$harvest_dir"   || rm -rf "$harvest_dir"
}

#############################

set -e

slave=
enter_only=

while getopts "hes:" key "$@"; do
    case "$key" in
	h)	showHelp;;
	e)	enter_only=1;;
	s)	slave=$OPTARG;;
	*)	echo "Use '-h' for more information" >&2; exit 1;;
    esac
done


slave_lock=
slave_started=
harvest_dir=
trap exitFunc EXIT

###########################

## execute sysconfig-script with inactive autoconfiguration
DJINNI_VSERVERNAME=
. /etc/sysconfig/fedora.us-build


slave=$($PKGLIBDIR/get-next-slave "$slave" "$@")
slave_lock=$SLAVE_LOCKDIR/$slave

shift $[ OPTIND - 1 ]

test "$enter_only" || test "$#" -eq 4 || {
    echo "Bad or missing options, use '-h'  for more information."
    exit 1
} >&2


## execute sysconfig-script with autoconfiguration to set e.g. special IPs
DJINNI_VSERVERNAME=$slave
. /etc/sysconfig/fedora.us-build



mnt="$SLAVE_MOUNTPOINT/$slave"

## Can fail since the 'chmod 000' barrier could be active...
/bin/mkdir -p "$mnt/root" &>/dev/null || :
/bin/chmod 0700 "$mnt"


$DJINNI -q new_bslave "$slave"
slave_started=1

cd "$mnt/root"

$SIMPLE_CHMOD 0 ../.

export _PS1="${1:+$1@}$slave# "
## Here, the real build starts...
$CHBIND --ip "$IP_SLAVE" --bcast "$BCAST_SLAVE" \
    $CHCONTEXT --secure --flag lock \
    /usr/sbin/chroot "." .$MACH_INIT "$@"

## Package was builded successfully, but slave can have malicious
## processes running. Since following checks will render slave area
## unusable, copy packages into our area first before proceeding.
harvest_dir=$(mktemp -d /tmp/build-harvest.XXXXXX)
$EXEC_CD /var/lib/mach/tmp   /bin/cp -a . $harvest_dir/


$DJINNI -q stop_bslave "$slave"
slave_started=


cp -a $harvest_dir/* /mnt/results