#!/bin/bash
# create-hera-stack.sh

die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 7 ] || die "Usage: ./create-hera-stack.sh <hera_host> <username> <password> <box_name> <hera_product> <stack_template> <configuration>"

# Example:
# ./create-hera-stack.sh hera.alfresco.me maurizio.pillitu@alfresco.com *** sltyapi038test1 chalfsalty chalfsaltystack onetrial

HeraInstance=$1
Username=$2
Password=$3
BoxName=$4
HeraProduct=$5
StackTemplate=$6
Configuration=$7

AlfrescoBuild=alfrescoenterprise-5.0.1-68
Duration=1
FirstName=FirstName
LastName=LastName
Company=AcmeCompany
Password=password

CookieFile=/tmp/cookie-hera
HeraUrl=https://$HeraInstance/api/v1/stacks/$HeraProduct
HeraAccount=TRIAL

echo "Collected Data:"
echo "BoxName: $BoxName"
echo "Username: $Username"
echo "HeraProduct: $HeraProduct"
echo "StackTemplate: $StackTemplate"
echo "Configuration: $Configuration"
echo "HeraUrl: https://$HeraInstance/api/v1/stacks/$HeraProduct"

csrf_token=$(curl -c $CookieFile -s -I -u $Username:$Password "$HeraUrl" | grep XSRF | awk '{print $2}' | rev | cut -c 2- | rev | sed 's/XSRF-TOKEN=/X-CSRF-TOKEN: /')

echo "TOKEN: $csrf_token"

curl -X POST -b $CookieFile -H "$csrf_token" \
-u $Username:$Password \
-F name=$BoxName -F account=$HeraAccount -F stack_template=$StackTemplate -F build=$AlfrescoBuild -F configuration=$Configuration -F premium=true -F region={} -F duration=$Duration -F init_var="{\"<<TRIAL_MARKETO_ID>>\" : 12345, \"<<TRIAL_USERNAME>>\" : \"$UserName\",\"<<TRIAL_FIRSTNAME>>\" : \"$FirstName\", \"<<TRIAL_LASTNAME>>\" : \"$LastName\", \"<<TRIAL_EMAIL>>\" : \"$Username\", \"<<TRIAL_COMPANY>>\" : \"$Company\", \"<<TRIAL_PASSWORD>>\" : \"$Password\"}" \
$HeraUrl

# rm -f $CookieFile
