#!/bin/bash

# generate random UUID for new SUV
# thanks https://stackoverflow.com/questions/34328759
SUV_ID=$(hexdump -vn8 -e'2/4 "%08x" 1 "\n"' /dev/urandom)
SUV_NAME=i-0$SUV_ID

# *** DO NOT REMOVE THE FIRST DOT ***
SUV_DOMAINNAME=".privatesuv.com"

SUV_IP_FIRST=$(shuf -i 10-200 -n 1)
SUV_IP_LAST=$(shuf -i 10-200 -n 1)
SUV_IP=10.9.$SUV_IP_FIRST.$SUV_IP_LAST

SUV_ALWAYS_PROVISION="false"

if [ "$1" == "--transient" ]; then
	shift
	
	SUV_ALWAYS_PROVISION="true"
	echo "initializing new TRANSIENT Mocha SUV with id $SUV_NAME"
else
	echo "initializing new PERSISTENT Mocha SUV with id $SUV_NAME"
fi

SUV_TEMPLATE="default"
if [ "$1" != "" ]; then

	SUV_TEMPLATE=$1

fi

if [ -d machines/$SUV_NAME ]; then
	echo "machine with ID $SUV_NAME already provisioned"
	exit;
fi

mkdir machines/$SUV_NAME
cd machines/$SUV_NAME

cp ../../templates/$SUV_TEMPLATE/$SUV_TEMPLATE.Vagrantfile ./Vagrantfile
cp ../../templates/$SUV_TEMPLATE/site.conf ./site.conf
cp ../../templates/$SUV_TEMPLATE/localhost.key .
cp ../../templates/$SUV_TEMPLATE/localhost.crt .
ln -s ../../templates/$SUV_TEMPLATE/mocha-libexec ./mocha-libexec
# cp ../../templates/default/default.box ./default.box
ln -s ../../templates/$SUV_TEMPLATE/sql ./sql
ln -s ../../templates/$SUV_TEMPLATE/site ./site
ln -s ../../templates/$SUV_TEMPLATE/libraries ./libraries

echo "enter sudo password to add entry to /etc/hosts if desired"

SUV_DNS=""
echo "$SUV_IP $SUV_NAME$SUV_DOMAINNAME" | sudo tee -a /etc/hosts
if [ $? == "0" ]; then
	SUV_DNS="$SUV_NAME$SUV_DOMAINNAME"
fi

if [ "$SUV_DNS" != "" ]; then
	SUV_IP_OR_DNS="$SUV_DNS"
else
	SUV_IP_OR_DNS="$SUV_IP"
fi

sed -i -e "s/@@MOCHA_SUV_ID@@/$SUV_NAME/" -e "s/@@MOCHA_SUV_ADDRESS@@/$SUV_IP/" -e "s/@@MOCHA_SUV_HOSTNAME@@/$SUV_IP_OR_DNS/" -e "s/@@MOCHA_ALWAYS_PROVISION@@/$SUV_ALWAYS_PROVISION/" Vagrantfile

vagrant up

