#!/bin/bash

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

if [ $# -eq 1 ]; then
	echo "about to create instance with image $1"	
	instanceid=$( ec2-run-instances $1 -k myAmiTestKey | egrep ^INSTANCE | cut --fields=2 );
	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";

	
	NOW=$(date +"%Y-%m-%d-%H-%M-%S");
	
	
	image=$(ec2-create-image -n "ami-$NOW" -d "this is my testing image"  "$instanceid" | cut -f2);
	echo "The created image is:$image";

	echo "now we are going to create image and it will wait for quite some minutes, be patient..."

	while [ 0 -eq 0 ]; do
		result=$(ec2-describe-images $image | cut -f5);


		if [ "$result" == "available" ]; then
			break;
		fi
		
		echo -n .;
		sleep 1;
	done

	echo -e "\nThe result status of image is:$result\n";

	echo "Now we are shutting down instance, it will take a few minutes, be patient..."
	
	while [ 0 -eq 0 ]; do
		
		terminate=$( ec2-terminate-instances "$instanceid" | cut -f3)
		if [ "$terminate" == "terminated" ]; then
			break;
		fi
		echo -n .;
		sleep 1;
	done
	echo -e "\nThe instance status:$terminate\n"
fi

