#!/usr/bin/env bash

set -euo pipefail

usage() { echo "Usage: $0 [-n <name>] [-t <type>] [-z <zone>]" 1>&2; exit 1; }

while getopts ":n:z:t:" o; do
    case "${o}" in
        n)
            name=${OPTARG}
            ;;
        t)
            type=${OPTARG}
            ;;
        z)
            zone=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${name}" ] || [ -z "${zone}" ] || [ -z "${type}" ]; then
    usage
fi

DIR=`dirname "$(readlink -f "$0")"`

# create vhome disk

vhome="${name}-vhome"
vhome_name="${vhome}"
vhome_size="500GB"
vhome_disk_type="pd-ssd"

gcloud compute disks create $vhome \
    --type $vhome_disk_type \
    --size $vhome_size \
    --zone $zone

# create ip address

get_region="gcloud compute zones list --filter='NAME=($zone)' --format='value(region)'"
region=`eval $get_region`
address="${name}-ip"

gcloud compute addresses create $address --region=$region

# create instance

boot_disk_size="30GB"
boot_disk_type="pd-ssd"
image_family="ubuntu-1804-lts"
image_project="ubuntu-os-cloud"
tags="http-server,https-server"

gcloud compute instances create $name \
    --boot-disk-size $boot_disk_size \
    --boot-disk-type $boot_disk_type \
    --image-project $image_project \
    --image-family $image_family \
    --address $address \
    --machine-type $type \
    --zone $zone \
    --disk name=$vhome,device-name=$vhome_name \
    --metadata-from-file startup-script=$DIR/gce-instance-startup.sh \
    --tags $tags

# delete startup-script

echo "run the following command once the instance has booted:"
echo "gcloud compute instances remove-metadata $name --zone $zone --keys=startup-script"
