#!/bin/bash
#
# $Id$
#
# Script build packages on various distributions with qemu
#

#if [ _"$1" = _"" ]; then
	#echo "Syntax: build2qemu [version-tag [vm1]..|vmx]] )"
	#exit -1
#fi

# Syntax: build2qemu [version-tag [--pkg "pkg1...pkgn"] [vm1]..|vmx]]

(
dname=`dirname $0`
prem=`echo $dname |cut -c1`
if [ _${prem} = _"/" ]; then
	export TOOLHOME=$dname
else
	export TOOLHOME=${PWD}/$dname
fi

. $TOOLHOME/common-env
. $TOOLHOME/distro-env
. $TOOLHOME/qemu-env

# We need to get $VER and $TAG
if [ "$1" = "" ]; then
	LAST=`cat ${TOPDIR}/LAST`
else
	LAST=$1
	shift
fi
VER=`echo $LAST | cut -d- -f1`
TAG=`echo $LAST | cut -d- -f2`
echo "Working on ${VER}-$TAG"

c=""
if [ _"$1" = _"--pkg" ]; then
	shift
	c=$1
	shift
fi

if [ _"$1" = _"" ]; then
	export VMS=`cat ${TOOLHOME}/DISTROS` 
	single=0
else
	export VMS="$*"
	single=1
fi

cat > $MONDOTMP/mkmondo << EOF
#!/bin/bash

export LANG="C"
export LANGUAGE="C"
export LC_ALL="C"
export TOOLHOME=$TOOLHOME

$TOOLHOME/build2pkg $LAST $c < /dev/null
$TOOLHOME/pkg2ftp $LAST $c
EOF
chmod 755 $MONDOTMP/mkmondo

if [ $single -eq 0 ]; then
	$TOOLHOME/file2ftp
fi

# TOPDIR contains ../.. which causes problems to tar
# so we need to recompute it
cd $TOPDIR
dir=`pwd`
tar cfz $MONDOTMP/mkmondo.tar.gz $TOOLHOME $MONDOTMP/mkmondo $dir/${VER}-$TAG

for m in $VMS; do
	echo "Working on $m"
	vmp=0
	if [ ! -f /users/qemu/$m.qemu ]; then
			echo "VM unaccessible. Verify NFS mount"
			rm -rf $MONDOTMP
			exit -1
	fi
	ps auxww | grep qemu | grep -v grep | grep -q /users/qemu/$m.qemu
	if [ $? -ne 0 ]; then
		# Virtual machine alreday started
		vmp=1
		$TOOLHOME/mkqemu $m &
		sleep 300
	fi
	scp -P $sp $MONDOTMP/mkmondo.tar.gz ~/.rpmmacros ~/.rpmrc bruno@localhost:
	rdate=`date "+%m%d%H%M"`
	ssh -q -p $sp root@localhost "date $rdate"
	ssh -q -p $sp bruno@localhost "cd / ; rm -rf ~bruno/mondo ~bruno/RPMS/BUILD/* ~bruno/RPMS/tmp/* /tmp/* ; tar xfz ~bruno/mkmondo.tar.gz ; $MONDOTMP/mkmondo " | tee $MONDOTMP/mkvm.log
	if [ $vmp -eq 1 ]; then
		ssh -q -p $sp root@localhost "halt -p"
		sleep 300
		proces=`ps auxww | grep qemu | grep -v grep | grep /users/qemu/$m.qemu | awk '{print $2}'`
		if [ "$proces" != "" ]; then
			kill $proces
			sleep 10
		fi
	fi
done

# Should be removed at the end
rm -rf $MONDOTMP
) 2>&1 | tee /tmp/build2qemu.log
