#!/bin/sh -e

if [ -z "$NOVA_USERNAME" ]; then
    echo "Please set \$NOVA_USERNAME before running this program."
    exit 1
fi
if [ $# -lt 2 ]; then
    echo "Usage: $0: <user_data_file> <size> [type]"
    exit 1
fi

if [ "$2" != small ] && [ "$2" != medium ] && [ "$2" != large ]; then
    echo "The size argument $2 should be small, medium, or large."
    exit 1
fi
if [ -n "$3" ]; then
    type="$3"
else
    type="ami-2"
fi
if [ ! -e "$1" ]; then
    echo "The file $1 does not exist."
    exit 1
fi
user_data_file="$1"
size="$2"

INSTANCE=
start_instance () {
echo "Starting instance."
INSTANCE="$(euca-run-instances --key $NOVA_USERNAME --user-data-file="$user_data_file" -t m1."$size" "$type" | tail -n1 | cut -f2)"
case "$INSTANCE" in
    i-*)
        ;;
    *)
        echo "Failed to start instance."
        exit 1
        ;;
esac
echo "Instance started: $INSTANCE"
}

start_instance

ret=
errors=0
timeout=0
while :; do
    echo -n .
    ret=$(euca-describe-instances $INSTANCE --ipv4 | tail -n1)
    if [ "$(echo "$ret" | cut -f6)" = error ]; then
        printf '\n'
        if [ $errors -gt 5 ]; then
            echo "Retry count exceeded; exiting."
            exit 1
        fi
        echo "Error starting instance; retrying."
        errors=$((errors+1))
        euca-terminate-instances $INSTANCE
        start_instance
        timeout=0
    fi
    if [ "$(echo "$ret" | cut -f6)" = running ]; then
        if [ -n "$(echo "$ret" | cut -f5)" ]; then
            ADDR="$(echo "$ret" | cut -f5)"
            break
        fi
    fi
    if [ $timeout -gt 80 ]; then
        echo "Timeout exceeded; exiting."
        exit 1
    fi
    sleep 3
    timeout=$((timeout+1))
done
printf '\n'
echo "Instance available: $ADDR"
timeout=0
while ! ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $ADDR sudo initctl status cloud-run-user-script | grep -qs stop/waiting; do
    printf "."
    if [ $timeout -gt 24 ]; then
        printf '\n'
        echo "Timeout exceeded; exiting."
        exit 1
    fi
    timeout=$((timeout+1))
    sleep 10
done
printf '\n'
echo "Ready."
