#! /bin/bash

# file: prep			G. Moody	21 December 2013
#				Last revised:	 6 January 2014
# Challenge 2014 evaluation, stage 1:  prepare an entry for evaluation

# Check the command-line arguments.
if [ $# -ne 2 ]; then
    echo "usage: $0 VIRTUALMACHINENAME ENTRYNAME"
    exit 1
fi

VM=$1
if [ "x$VM" = "x" ]; then
    echo "$0: |$VM| is not a valid virtual machine name";
    exit 1
fi

EN=$2
# Check entry name, reject if improper.
case "$EN" in
  *entry.tar.gz) SE=entry.tar.gz ;;
  *entry.zip)    SE=entry.zip ;;
  *) echo "Improper name ($EN) for entry"
     exit 1 ;;
esac

cp -p $EN $WDIR/$SE
cd $WDIR

cat >prep.sh <<EOF
#! /bin/bash

# Work in the user's home directory, because the root file system is read-only.
cd

VM=$VM
EN=$SE

# File to be used to log errors, warnings, or success.
LOG=log.txt

case \$EN in
  entry.tar.gz) if ! tar xfz /media/cdrom0/entry.tar.gz >/dev/null 2>&1; then
		    echo "entry.tar.gz cannot be unpacked"
		    exit 1
		fi ;;
  entry.zip)    if ! unzip /media/cdrom0/entry.zip >/dev/null 2>&1; then
		    echo "entry.zip cannot be unpacked"
		    exit 1
		fi ;;
  *)		echo "invalid entry name (\$EN)"
		exit 1 ;;
esac

# Check to see if all required components are present, reject if not.
EX=0
if [ ! -s setup.sh ]; then
    echo "Script 'setup.sh' is missing"; EX=1;
fi
if [ ! -s next.sh ]; then
    echo "Script 'next.sh' is missing"; EX=1;
fi
if [ ! -s AUTHORS ]; then
    echo "Text file 'AUTHORS' is missing"; EX=1;
fi
if [ ! -d sources ]; then
    echo "Directory 'sources' is missing"; EX=1;
fi
if [ ! -d challenge ]; then
    echo "Directory 'challenge' is missing"; EX=1
elif [ ! -d challenge/2014 ]; then
    echo "Directory 'challenge/2014' is missing"; EX=1
elif [ ! -d challenge/2014/set-p ]; then
    echo "Directory 'challenge/2014/set-p' is missing"; EX=1
else
    for R in \`seq 100 199\`
    do
	if [ ! -e challenge/2014/set-p/\$R.qrs ]; then
	    echo "Annotation file '\$R.qrs' is missing"; EX=1
	fi
    done
fi
if [ \$EX -ne 0 ]; then
    echo "Required component(s) missing -- not scored"
    exit 1
fi

# Compile or perform other one-time initialization of the entry.
if ! timeout -k 300 300 /bin/bash ./setup.sh >\$LOG 2>&1; then
    case \$? in
	124) echo "setup.sh: timed out after 5 minutes" ;;
	  *) if [ ! -s \$LOG ]; then
                 echo "setup.sh: unknown error" >\$LOG
	     fi ;;
    esac
    cat \$LOG
    exit 1   # quit if error or timeout in setup.sh
fi

echo success
exit 0
EOF

chmod +x prep.sh

# Run the script generated by prep in the VM.
$BVM exec -n $VM --rw -c './prep.sh' prep.sh $SE

exit 0
