#!/bin/bash
# Prereqs:
# - terraform
# First we run: terraform get -update
# Next we check if the s3 bucket exists, if it does not we create it
# Finally we setup the remote state config

bucket="tw-devtools"
backend="S3"
repo="dta/tf_tabot"
suffix="staging"

if [ ! $(which terraform) ]; then
  echo "Please install terraform and ensure it is in your $PATH"
  exit 1
fi

# Grab our modules, if any...
echo "Running 'terraform get -update'"
terraform get -update

if [ $? -gt 0 ]; then
  echo "Failed running 'terraform get -update'"
  exit 1
fi

# Store the tfstate for the bucket in the bucket
echo "Setting up remote tfstate to ${backend} with key ${bucket}/tfstate/${repo}/${suffix}"
terraform remote config \
  -backend=$backend \
  -backend-config="bucket=${bucket}" \
  -backend-config="key=tfstate/${repo}/${suffix}"

if [ $? -gt 0 ]; then
  echo "Failed running terraform remote config"
  exit 1
fi

exit 0
