#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

ami_import=""
s3_import=""
today=$(date +%Y-%m-%d.%HH%Mmin%S)
BUCKET=${3:-cloug-vms}
IMG_NAME=${1:-current.img}
DESC=${2:-"${USER} ${today}"}

function finish {
    if [[ ! -z "$ami_import" && -e $ami_import ]]; then
        rm $ami_import
    fi
    if [[ ! -z "$s3_import" && -e $s3_import ]]; then
        rm $s3_import
    fi
}

trap finish EXIT

if [ $# == 0 ]; then
        echo "$(basename $0) IMG_TO_IMPORT [\"a description\"] [BUCKET_NAME]"
        exit 0
fi

S3_IMPORT="
{
	\"Description\": \"${DESC}\",
	\"Format\": \"raw\",
	\"UserBucket\": {
		\"S3Bucket\": \"${BUCKET}\",
		\"S3Key\": \"${IMG_NAME}\"
	}
}
"

aws s3 cp ${1:-current.img} s3://$BUCKET

s3_import=$(mktemp)
echo ${S3_IMPORT} > ${s3_import}
import_id=$(aws ec2 import-snapshot --description ${DESC} --disk-container file://${s3_import} | grep ImportTaskId | grep ImportTaskId | awk -F: '{print $2}' | sed "s/[ \",]//g")

echo "Wainting for snapshot with import id : $import_id"
_SNAP=""
while [[ -z ${_SNAP} ]]; do
	_SNAP=$(aws ec2 describe-import-snapshot-tasks --import-task-ids $import_id | grep "Status" | grep "complete" ) || true
	echo -n "."
	sleep 5
done
rm $s3_import
echo ""

_SNAP=$(aws ec2 describe-import-snapshot-tasks --import-task-ids $import_id | grep SnapshotId | grep -Eo "snap-[[:alnum:]]*")

echo "Snaphot Id ${_SNAP}"
echo "Import as AMI"

AMI_IMPORT="
[
  {
    \"DeviceName\": \"/dev/sda1\",
    \"Ebs\": {
      \"SnapshotId\": \"${_SNAP}\",
      \"VolumeType\": \"gp2\"
    }
  }
]
"

ami_import=$(mktemp)
echo "$AMI_IMPORT" > ${ami_import}
ami=$(aws ec2 register-image --name "$DESC" --architecture x86_64 --virtualization-type hvm --root-device-name "/dev/sda1" --block-device-mappings file://${ami_import})

rm $ami_import
echo ${ami}

echo "Done"

