#!/bin/bash

BASE_D="/mnt/wd"

Usage() {
   cat <<EOF
Usage: ${0##*/} config
  Test ec2-bundle-vol.

  Requires ec2-api-tools. Should be called from inside an image.

  Usage:
  * launch instance; rhost=ec2-.....
  * credd=\$(bash -c '. config && echo \$CRED_D')
  * ssh ubuntu@\$rhost 'sudo mkdir -p $BASE_D && \\
      sudo chown ubuntu:ubuntu $BASE_D'
  * rsync -azv config test-bundle-vol common ubuntu@\$rhost:$BASE_D
  * rsync -azv \${credd%/}/ ubuntu@\$rhost:$BASE_D/creds
  * ssh ubuntu@\$rhost
  * % sed -i 's,CRED_D=.*,CRED_D=$BASE_D/creds,' $BASE_D/config
  * % cd $BASE_D
  * % ./test-bundle-vol config
EOF
}
[ "$1" = "-h" -o "$1" = "--help" ] && { Usage; exit 0; }

my_d=$(dirname $(readlink -f "${0##*/}"))
. "${my_d}/common" || { echo "failed to find 'common'"; exit 1; }

[ -f "$1" ] || { Usage 1>&2; fail "must give argument for config"; }

config "$1"

ARCH=$(uname -m)
case $ARCH in
   i?86) ARCH=i386;
esac
BUNDLE_D=$BASE_D/bundle
tmpf="$TEMP_D/tmp"

run "rm -rf BUNDLE_D" sudo rm -Rf "$BUNDLE_D"
run "mkdir -p BUNDLE_D" mkdir -p "$BUNDLE_D"

error "# may take quite a long time (10s of minutes)"

run "load module" sudo sh -c 'modprobe loop || :'
# this leaves /home/ubuntu/.ssh keys in place so that we could potentially
# actually ssh to the image.
run "bundle-vol" \
  sudo -E ec2-bundle-vol  --arch "$ARCH" \
  --destination "$BUNDLE_D" \
  --prefix "testbundle.img" \
  --user $EC2_USER_ID \
  --size 10240 \
  --exclude /mnt,/root/.ssh \
  $KEY_ARGS

run "perms to user" \
  sudo chown -R "$(id -u):$(id -g)" "$BASE_D"

if [ "${DRY_RUN:-0}" = "0" ]; then
  region=$(ec2metadata --availability-zone) &&
    region=${region%[a-z]} || region="us-east-1"
  sgroup=$(ec2metadata --security-group) || sgroup="default"
  if ! itype=$(ec2metadata --instance-type); then
     [ "$ARCH" = "i386" ] && itype="m1.small" || itype="m1.large"
  fi
  # newer versions of ami tools exclude .ssh/authorized_keys
  # so we have to launch with a key
  if [ -z "$EC2_KEY_PAIR" ]; then
    mdurl="http://169.254.169.254/2009-04-04/meta-data/"
    out=$(wget -O - "$mdurl/public-keys")
    key="${out#0=}"
  fi
else
  echo "# get current availability-zone, security-group, instance-type, keypair"
  echo "#   from metadata service using ec2metadata"
  itype="m1.small"
  region="us-east-1"
  sgroup="default"
  key=${EC2_KEY_PAIR:-"default"}
fi

bucket="${BUCKET_BASE}-$region"
manifest="testbundle.img.manifest.xml"

run "uploading to $bucket in $region with no location argument" \
  ec2-upload-bundle $SECRET_ARGS --bucket $bucket \
  --manifest "$BUNDLE_D/$manifest"
CLEAN_DELETE_BUNDLE="$bucket $BUNDLE_D/$manifest"

run "registering $bucket/$manifest in region $region" \
  ec2-register --region $region \
  --name "$bucket/${manifest%.manifest.xml}" \
  $XKEY_ARGS "$bucket/$manifest" > "$tmpf"
read a ami_id < "$tmpf"
CLEAN_DEREGISTER="$region $ami_id"

run "run instance of $ami_id" \
   ec2-run-instances --region $region $XKEY_ARGS \
   --key "${key}" \
   $ami_id --group $sgroup --instance-type $itype > "$tmpf"
{ read res id other; read instance inst_id other; } < "$tmpf"
CLEAN_INSTANCE_ID=$inst_id

cat <<EOF
 *** Hit enter to finish ***
 You have to wait until $inst_id is running as this will
 delete its bundle in $bucket/$manifest
 ***                     ***
EOF
read

error "ran instance as $inst_id, remember to kill it"
