#!/bin/bash
# This is a little chicken and egg, we need to create the S3 bucket before we can upload the state.
# Prereqs:
# - terraform
# - aws cli
# - assumes your credentials to aws cli are setup and/or available via env vars
# 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="tf-state-bucket"
backend="S3"
repo="qa/terraform"
suffix="accounts/twitch-qa-aws/s3/tf-state-bucket"

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

if [ ! $(which aws) ]; then
  echo "Please install aws cli tools and ensure they are 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

# Run terraform apply, if our bucket doesn't exist
echo "Checking if S3 bucket ${bucket} exists"
aws s3 ls $bucket >/dev/null 2>&1
bucket_exist=$?

# If bucket doesn't exist, create it
if [ $bucket_exist -gt 0 ]; then
  echo "Bucket ${bucket} doesn't exist.  Creating it now"
  terraform apply

  if [ $? -gt 0 ]; then
    echo "Failed running 'terraform apply'"
    exit 1
  fi
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

if [ -f terraform.tfstate.backup ]; then
  rm -f terraform.tfstate.backup
fi

exit 0
