#!/bin/bash

#script s3-folder object-name description

if test "$#" -ne 3; then 
	echo "Usage ./s3vmdktosnapshot s3-folder object-name description"
else
	echo "Deleting old vmimport role"
	aws iam delete-role-policy --role-name vmimport --policy-name vmimport 
	aws iam delete-role --role-name vmimport 

	folder=$1
	object=$2
	description=$3
	trustpolicy="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"vmie.amazonaws.com\"},\"Action\":\"sts:AssumeRole\",\"Condition\":{\"StringEquals\":{\"sts:Externalid\":\"vmimport\"}}}]}"
	rolepolicy="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:GetBucketLocation\",\"s3:GetObject\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::$folder\",\"arn:aws:s3:::$folder/*\"]},{\"Effect\":\"Allow\",\"Action\":[\"ec2:ModifySnapshotAttribute\",\"ec2:CopySnapshot\",\"ec2:RegisterImage\",\"ec2:Describe*\"],\"Resource\":\"*\"}]}"

	echo "Creating vmimport role"
	aws iam create-role --role-name vmimport --assume-role-policy-document $trustpolicy > /dev/null 2>&1
	aws iam put-role-policy --role-name vmimport --policy-name vmimport --policy-document $rolepolicy > /dev/null 2>&1

	import="{\"Description\":\"$description\",\"Format\":\"vmdk\",\"UserBucket\":{\"S3Bucket\":\"$folder\",\"S3Key\":\"$object\"}}"
	echo "Submitting S3 to EC2 conversion job"
	taskId=$(aws ec2 import-snapshot --disk-container $import 2>&1 | jq -r .ImportTaskId)
	echo "task ID = "$taskId

	sleep 2
	status=pending
	while [[ ! $status =~ "completed"|"deleted"  ]]
	do
		output=$(aws ec2 describe-import-snapshot-tasks --import-task-ids $taskId 2>&1)
		#echo $status
		status=$(echo $output | jq -r '.ImportSnapshotTasks.[].SnapshotTaskDetail.Status')
		message=$(echo $output | jq -r '.ImportSnapshotTasks.[].SnapshotTaskDetail.StatusMessage')
		#status=$(aws ec2 describe-import-snapshot-tasks --import-task-ids $taskId 2>&1 | jq -r '.ImportSnapshotTasks.[].SnapshotTaskDetail.StatusMessage')
		echo "Status = "$status";  Message = "$message
		sleep 5
	done
fi
