#!/bin/sh

# ami-2675974f = Ubuntu 9.10 server i386 5Gb EBS
# ami-916c81f8 = my snapshot: Ubuntu 9.10 server i386 5Gb EBS
AMI=ami-916c81f8

USER=ubuntu
KEY=simonmar-us-east-keypair

PWD=`pwd`

# ec2-run-instances ami-916c81f8 -b /dev/sdc=ephemeral0 -k simonmar-us-east-keypair -t m1.small

ec2-request-spot-instances \
  ${AMI} \
  --price 0.08 \
  --type one-time \
  -k ${KEY} \
  -t c1.medium

# This doesn't work; it seems to be already enabled in my snapshot
#  -b /dev/sdc=ephemeral0 \

echo -n waiting for instance startup...
while true; do
   instance=`ec2-describe-instances | grep "${AMI}.*running"`
   if [ "$instance" != "" ]; then break; fi
   sleep 1
   echo -n .
done

EC2_HOST=`echo $instance | cut -d ' ' -f 4`

echo ${EC2_HOST}

cp ~/.ssh/config ~/.ssh/config.old
sed <~/.ssh/config >~/.ssh/config.new "s|Hostname ec2.*amazonaws.com|Hostname ${EC2_HOST}|;s|IdentityFile .*pem|IdentityFile ${PWD}/${KEY}.pem|"
mv ~/.ssh/config.new ~/.ssh/config
chmod 600 ~/.ssh/config

# copy some files up
if test -f ~/.screenrc; then
  scp prep_instance validate ~/.screenrc ec2:
fi

# prep the instance (mount the ephemeral drive etc.)
ssh ec2 sh prep_instance

echo "to log in:              ssh ec2"
echo "to log in with screen:  ssh -t ec2 screen -R"
echo "to push patches to EC2: ./darcs-all --checked-out -r ec2:ghc push"
echo "to validate GHC:        ssh ec2 sh validate"
echo "to shut down:           ssh ec2 sudo halt"

