#!/usr/bin/env bash
args="$@"

###############################
# Download the terraform binary
###############################
function downloadTerraformBinary()
{
  targetDir=$1
  releaseSource=$2
  terraformZip="${targetDir}terraform.zip"
  curl --max-time 300 -o $terraformZip $releaseSource
  unzip -o -d $targetDir $terraformZip
  rm -f $terraformZip
}

thisScript=$0
targetDir=${thisScript%"tfw"}

propFile="${targetDir}terraform-maven.properties"
search="="
################################################################
# read all lines from the properties file and store in variables
################################################################
while IFS= read -r line
do
  case $line in
  *"distributionSite"*)
    distributionSite=${line#*$search}
    ;;
  *"releaseDir"*)
    releaseDir=${line#*$search}
    ;;
  *"releaseName"*)
    releaseName=${line#*$search}
    ;;
  *"releaseVer"*)
    releaseVer=${line#*$search}
    ;;
  *"releaseOS"*)
    releaseOS=${line#*$search}
    ;;
  *"releaseSuffix"*)
    releaseSuffix=${line#*$search}
    ;;
  esac
done < "$propFile"

#################################################################################
# Construct the full zip file name, full binary file name, and URL of the package
#################################################################################
terraformBinary="${targetDir}terraform"
releaseSource="${distributionSite}/${releaseDir}/${releaseVer}/${releaseName}_${releaseVer}_linux_${releaseSuffix}"

##########################################################################
# if the terraform binary is already there, figure out what version it is
##########################################################################
if [[ -f $terraformBinary ]]
then
  versionString=`$terraformBinary -version`
  search="Terraform v"
  rest=${versionString#*$search}
  installedVerion=`echo $rest|cut -d ' ' -f 1`

###############################################################
# if the terraform binary is already there, check if it is the
# same version as the properties file indicates
# if not, download and install the desired version
###############################################################
  if [[ $installedVerion == "$releaseVer" ]]
  then
    echo ""
  else
    echo "Different version, downloading"
      downloadTerraformBinary $targetDir $releaseSource
  fi
else
############################################
# if the terraform binary is not there,
# download and install the desired version
############################################
  echo "Terraform not found, installing"
  downloadTerraformBinary $targetDir $releaseSource
fi

###################################################
# Run terraform with the supplied arguments if any
###################################################
$terraformBinary $args
exit
