#!/bin/sh
# 2005-2006 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain
#
# Get shell in hasher with apt and mc
# -t - use test hasher
# -i - initialize hasher
# -M? - set target distro
# Public domain
# TODO: -r

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common
load_mod hasher rpm

SAVEOPT=$@

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

Usage="Usage: $name [-t -i -h -r] bin.rpm..."
function mygetopts()
{
name=${0##*/}
Descr="$name - install package in hasher / take shell"

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echog "Options:"
	echog " -i - initialize hasher"
	echog " -c - cleanup hasher"
	echog " -t - use test hasher dir"
	echog " -r - remote login to hasher"
}

while getopts :chitr opt; do
    case $opt in
    h) phelp; exit 0;;
    t) HASHERDIR=$HASHERDIR-test; TESTMODE=1 ;;
	i) INITIALIZE=1 ;;
	c) CLEANUP=1 ;;
	r) REMOTE=1 ;;
    +?) echog "$name: options should not be preceded by a '+'." 1>&2; exit 2;;
#    ?)  echog "$name: $OPTARG: bad option.  Use -h for help." 1>&2 ; exit 2;;
	?) OPTIND=$((OPTIND-1)); break;
    esac
done

# remove args that were options
if [ $# -gt 0 ]; then 
	shift $((OPTIND - 1))
fi

LISTRPMARGS=$@
}

parse_cmd_pre "$@" --

HASHERDIR=$HASHERDIR$MENVARG

HSH=/usr/bin/hsh
if [ ! -x "$HSH" ] ; then
	echo "Please install hasher package before use it"
	exit 1
fi


mygetopts $LISTARGS

if [ -n "$REMOTE" ] ; then
	check_key
	test -n "$BUILDSERVER" || fatal "Please set BUILDSERVER in config file"
	ssh -t $BUILDSERVER loginhsh ${SAVEOPT/-r/}
	exit 0
fi

if [ "$CLEANUP" = "1" ]; then
	echog "Cleanup $HASHERDIR ..."
	$HSH --cleanup-only $HASHERDIR || fatal "cleanup"
	exit 0
fi

if [ ! -d $HASHERDIR -o "$INITIALIZE" = "1" ]; then
	echog "Initialize $HASHERDIR ..."
	mkdir -p $HASHERDIR && $HSH --initroot-only $HASHERDIR || fatal "mkdir"
fi

SHELLHASHERARG="--mountpoints=/proc"

check_locking

echog "Prepare hasher in $HASHERDIR ..."
# there is package names in LISTRPMARGS
UTILPKG="mc"
# FIXME: gnome program needs dbus-tools-gui
if [ -n "$TESTMODE" ] ; then
	UTILPKG="$UTILPKG XFree86-xauth fonts-ttf-liberation"
else
	UTILPKG="$UTILPKG etersoft-build-utils"
fi
$HSH-install $HASHERDIR --wait-lock $UTILPKG $LISTRPMARGS $LISTNAMES || fatal "Error with install"
echog "You are in hasher shell"
$HSH-shell $HASHERDIR $SHELLHASHERARG -Y --shell
if [ -n "$TESTMODE" ] ; then
	echo "Remove package for test preun scripts"
	$HSH-run --rooter $HASHERDIR -- rpm -e $(drop_pkg_extensions $LISTNAMES)
	echo "Cleanup hasher..."
	$HSH --cleanup-only $HASHERDIR
fi
