#!/bin/bash -x
# run a test within cloud.suse.de
function usage()
{
  echo "usage: export OS_USERNAME=xx ; export OS_PASSWORD=xx ; source $0 ; startvm ; runtest"
}

function setup()
{
    if rpm -q python-novaclient >/dev/null ; then
      return # only needed once
    fi
    # setup tiny VM for jenkins
    #zypper rr 1 # remove DVD repo
    zypper ar http://download.suse.de/install/SLP/SLES-11-SP2-LATEST/x86_64/DVD1/ sle11sp2latest
    zypper ar http://download.suse.de/install/SLP/SLE-11-SP2-SDK-LATEST/x86_64/DVD1/ sle11sp2sdklatest
    zypper ar http://download.suse.de/install/SLP/SLE-11-SP2-CLOUD-GM/x86_64/DVD1/ C1-GM
    zypper --gpg-auto-import-keys -n ref
    zypper --non-interactive in python-novaclient
    mkdir -p ~/.ssh
    echo ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAp8fBkDaecZtoueQIRsZFNgmyMo++gY7+6YlbaJqJNS1nsredp8Rjs53pwVUa4tyewKJ+mZDDMwgbZdePn3QXbavuzdNDUhswNlEDdhrdDn44QciwBcpsf/AMtqpfdl8uGS5wl0ZfDt5m9ovYUeg49ZiIWx5qP5nmiIfgLHW4pVN673Sl9gT2wGo05x/PiU7B+M80AMunJWU1a58UmrQ1panxCjm8mMcmddd6tuTdTYEFNBSc2TIaZzZ4m7N98DYn+LtiXkov7fAO2Vnne5JKL8fpx1KGxKhLhkjTBVjrD6JVUlg2QlljxIXeV8xu+6YsSZca08jilRrxwDvRbk4oYQ== hudson@hudsoninscance >> ~/.ssh/authorized_keys
}


function cleanupvm()
{
    #cleanup prev
    for instance in $(nova list| perl -ne 'if(/^\| (\S+) .*jenkins-testvm /){print $1}') ; do
      nova delete $instance
    done
    nova delete jenkins-testvm || true
    sleep 10
}


function startvm()
{
    cleanupvm
    test "$DevelCloudHead" != "false" && export OSHEAD=1
    test -z $OS_USERNAME && usage && exit 1
    test -z $OS_PASSWORD && usage && exit 1

    image=${image:-SP2-64}
    sshkey=${sshkey:-jenkins}
    nova boot --flavor d2.small --image $image --key_name $sshkey jenkins-testvm > boot.out
    instanceid=`perl -ne 'm/ id [ |]*([0-9a-f-]+)/ && print $1' boot.out`
    sleep 20 # time to prepare
    export ip=$(nova floating-ip-list| perl -ne 'm/^\|\s*(\d+\.\d+\.\d+\.\d+)\s*\|\s*None/ && print($1) && exit 0')
    nova add-floating-ip $instanceid $ip
    test -n "$ip" || exit 17
    n=300 ; while test $n -gt 0 && ! ping -q -c 1 -w 1 $ip >/dev/null ; do # wait for VM to become reachable
      n=$(expr $n - 1)
      echo -n "."
    done
    echo "finished waiting for VM: $n counts left"
    sleep 70 # extra time for ssh to start
}


function runtest()
{
    test -n "$ip" || exit 18
    ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@$ip "export cloudsource=${cloudsource}; export OSHEAD=${OSHEAD}; export NONINTERACTIVE=1; init 3; curl https://raw.github.com/SUSE-Cloud/automation/master/scripts/jenkins/qa_openstack.sh|bash -x"
    exit $?
}

### MAIN
setup

# Hint:
# watch "ps ax|tail -16" # use on test-VM for manual watching
