#!/bin/bash

pem="/home/nick/Desktop/Amazon/ami-test/myAmiTestKey.pem"

	if [ $# -eq 1 ];  then
		ami=$1;
	else
		ami=$(cat ami.txt);
	fi

	NOW=$(date +"%Y-%m-%dT%H-%M-%S");
	echo "about to create instance with image $ami "	
	spotrequestid=$( ec2-request-spot-instances  $ami -k myAmiTestKey -z us-east-1d --price 0.08   | egrep ^SPOTINSTANCEREQUEST | cut --fields=2 );

	echo "spotrequestid=$spotrequestid"

	while instanceid=$(ec2-describe-spot-instance-requests "$spotrequestid" | egrep ^SPOTINSTANCEREQUEST | cut --fields=12) && test -z $instanceid; do
		echo -n .;
		sleep 1;
	done 

	echo "instanceid=$instanceid"

	echo "instance created successfully and now wait for it being ready..."
	while host=$(ec2-describe-instances "$instanceid" | egrep ^INSTANCE | cut -f4) && test -z $host; do 
		echo -n .; 
		sleep 1; 
	done
	
	echo -e "\nThis is the host:$host";
	echo $host > host.txt
	echo $instanceid>id.txt

	echo ssh -i $pem ubuntu\@$host
	


