#!/bin/sh

if [ $# -ne 2 ]
then
	echo "use: $0: <config-file> <image-name>"
	exit 1
fi

configFile=$1
imageName=$2

echo -n "Checking for aws command in PATH..."
if which aws >/dev/null 2>&1
then
	echo "ok"
else
	echo "failed"
	echo "$0: The \"aws\" command must be in your path to use this script."
	exit 1
fi

echo -n "Checking for aws configuration..."
if [ -f ~/.aws/config ]
then
	echo "ok"
else
	echo "failed"
	echo "$0 You must run \"aws configure\" before using this script."
	exit 1
fi

echo -n "Checking for correct credentials..."
if aws ec2 describe-instances > /dev/null 2>&1
then
	echo "ok"
else
	echo "failed"
	echo "$0: Your Amazon credentials are not set up correctly. Try \"aws ec2 describe-instances\" to troubleshoot."
	exit 1
fi

CIDR_BLOCK=10.0.0.0/16
SUBNET_CIDR_BLOCK=10.0.1.0/24
UUID="$(uuidgen)"
KEYPAIR_NAME=kp.${UUID}
SECURITY_GROUP_NAME=sg.${UUID}

echo "Creating virtual private cluster..."
VPC=`aws ec2 create-vpc --cidr-block $CIDR_BLOCK --output text | cut -f 7`

echo "Creating subnet..."
SUBNET=`aws ec2 create-subnet --cidr-block $SUBNET_CIDR_BLOCK --vpc-id $VPC --output text | cut -f 9`
aws ec2 modify-subnet-attribute --subnet-id $SUBNET --map-public-ip-on-launch

echo "Getting default security group of VPC $VPC..."
SECURITY_GROUP=`aws ec2 describe-security-groups --filters Name=vpc-id,Values=$VPC --query 'SecurityGroups[0].GroupId' --output text`

echo "Configuring security group $SECURITY_GROUP..."
# Allow for ssh incoming traffic
aws ec2 authorize-security-group-ingress --group-id $SECURITY_GROUP --port 22 --cidr 0.0.0.0/0 --protocol tcp

echo "Creating internet gateway..."
GATEWAY=`aws ec2 create-internet-gateway --output text | cut -f 2`

echo "Attaching internet gateway..."
aws ec2 attach-internet-gateway --internet-gateway-id $GATEWAY --vpc-id $VPC

echo "Looking up route table..."
ROUTE_TABLE=$(aws ec2 describe-route-tables --filters Name=vpc-id,Values=$VPC --query 'RouteTables[0].RouteTableId' --output text)

echo "Creating route..."
aws ec2 create-route --route-table-id $ROUTE_TABLE --gateway-id $GATEWAY --destination-cidr-block 0.0.0.0/0

echo "Creating keypair $KEYPAIR_NAME..."
# Remove junk from around keypair that confuses ssh.
aws ec2 create-key-pair --key-name $KEYPAIR_NAME --output text | sed 's/^.*\t-----/-----/' | sed 's/KEY-----.*$/KEY-----/'i > $KEYPAIR_NAME.pem

# Permissions must be just so for ssh to be happy.
chmod 600 $KEYPAIR_NAME.pem

echo "Creating $configFile with all the details..."

cat > $configFile <<EOF
{
"vpc" : "$VPC",
"subnet" : "$SUBNET",
"gateway" : "$GATEWAY",
"route_table" : "$ROUTE_TABLE",
"security_group_id" : "$SECURITY_GROUP",
"security_group_name" : "$SECURITY_GROUP_NAME",
"keypair_name" : "$KEYPAIR_NAME",
"ami" : "$imageName",
}
EOF

echo "Done!"
