#!/usr/bin/env bash

set -eo pipefail

usage() {
    cat <<EOF
$0 <env> [--clean]

Sets up a terraform workspace for the account and then sets up
account-level infrastructure on the account as well
EOF
    exit 1
}

if [ -z "$1" ] || [  "$1" = "-h" ] || [ "$1" = "--help" ]; then usage; fi
CLEAN=false
if [[ $2 == "--clean" ]]; then 
    CLEAN=true
fi

set -u

TF_VARFILE="vars-${1}.tfvars"
cd  $(dirname "$0")

if [[ ! -f ${TF_VARFILE} ]]; then
    echo "Please make a tfvars file ${TF_VARFILE}"
    exit 1;
fi

terraform workspace select "$1" || terraform workspace new "$1"
# We need to know some VPC-level magic strings before we can run an apply
# against the whole thing
if ${CLEAN}; then 
    terraform apply --var-file="${TF_VARFILE}" -target module.default_vpc
fi
terraform apply --var-file="${TF_VARFILE}"
