#!/bin/bash -x

date

source ~/common/globaldefs.sh
source ~/targets/${1}/defs.sh
source ~/common/fun.sh
CURR_TARGET=$1

shift
PREPARE=
while [ -n "$*" ]; do
    flag=$1
    value=$2

    case "$flag" in
        "--prepare")
            PREPARE=true
            shift
        ;;
        *)
            echo -e "unknown option $flag\n"
        ;;
    esac
    shift
done

pwd
pushd "$DATA_DIR"
# remove unprocessed reports
rm -f data/*.tar.gz
if [ ! -d data ]; then
    mkdir data
fi

# if PREPARE is set, we only reinstall the VMs and die
if [ $PREPARE ]; then
    recreate_vm
    exit 0
fi

reinit_vm

virsh --connect qemu:///system start "${VM_NAME}_clone"
if [ $? != 0 ]; then
   # how about we create it here instead of dying??
   echo "VM with name ${VM_NAME}_clone does not exist!"
   exit 1;
fi

set +x
try=0

while true; do
  IP=$( ~/bin/virt_addr --system ${VM_NAME}_clone )

  res=$?;
  if [ $res == 0 ]; then
    break;
  fi;

  if [ $try == 100 ]; then # max tries
     echo "Unable to get IP of the VM";
     exit 1;
  fi
  let try=try+1;
  sleep 1; # wait between the attempts, otherwise it floods the log
done

set -x

wait_for_vm

echo "Giving the sshd a while to start"
sleep 5

set +x
try=0

while true; do
  scp -o StrictHostKeyChecking=no ~/targets/runtests.sh \
    ~/targets/$CURR_TARGET/config.sh.local root@$IP:~

  res=$?;
  if [ $res == 0 ]; then
    break;
  fi;

  if [ $try == 100 ]; then # max tries
     echo "Can't upload runtests.sh to VM";
     exit 1;
  fi
  let try=try+1;
  sleep 1; # wait between the attempts, otherwise it floods the log
done

while true; do
  ssh -o StrictHostKeyChecking=no root@$IP "sh ./runtests.sh"
  res=$?;
  if [ $res == 0 ]; then
    break;
  fi;

  if [ $try == 100 ]; then # max tries
     echo "Seems like machine '$VM_NAME' doesn't want to talk with us on '$IP'"
     exit 1;
  fi
  let try=try+1;
  sleep 1; # wait between the attempts, otherwise it floods the log
done

date
echo -n "Zzzz (until VM is executing the tests): "
while virsh --connect qemu:///system list | grep -q $VM_NAME; do
    echo -n '.'
    sleep 1m
done
echo -n 'x'
set -x
date

handle_results "$DATA_DIR/data/" "/var/nightly_results/$( basename $DATA_DIR/)"
echo $result_path
date
test -d $result_path || exit 1
echo 'Mirroring website'
~/web_mirror/cron_wrapper
date
echo 'Send email'
res_mail $result_path
date

popd # $DATA_DIR
echo 'All done'
