#!/bin/bash

TOP_LEVEL=${PWD}

usage() {
  printf "\nUsage: \n\n./update-module-version.sh -v <module version tag> -m <module repo name>\n\n"
  exit 1
}

while getopts ":m:v:" opt; do
  case $opt in
    m)
      MODULE_NAME="${OPTARG}"
      ;;
    v)
      MODULE_VERSION="${OPTARG}"
      ;;
    [?])
      echo "Invalid option: -$OPTARG" >&2
      usage
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      usage
      ;;
  esac
done

if [[ "${MODULE_NAME}" == "" || "${MODULE_VERSION}" == "" ]]; then
  printf "\nPlease provide both a module name and module version tag\n"
  usage
fi

TAG_EXISTS=$(git ls-remote --tags git@github.com:theorchard/"${MODULE_NAME}" | grep -c "refs/tags/${MODULE_VERSION}$")

if [ "${TAG_EXISTS}" == "0" ]; then
  printf "Tag %s does not exist in repo git@github.com:theorchard/%s\n" "${MODULE_VERSION}" "${MODULE_NAME}"
  usage
fi

update_module_versions () {
  env=$1
  printf "Updating version of %s to %s for env %s\n" "${MODULE_NAME}" "${MODULE_VERSION}" "${env}"
  for folder in ./"${env}"/*; do
    cd "${TOP_LEVEL}/${folder}" || (printf "\nDirectory %s does not exist\n" "${TOP_LEVEL}/${folder}" && exit 1)
    printf "Project: %s\n" "${TOP_LEVEL}/${folder}"
    # I'm really sorry about this
    # Find all terraform files within the folder for each one:
    # If an existing "?ref=" exists in the source, lop it off (does nothing if no ref specified)
    # Then re-add a ref using the specified module version
    find . -name "*.tf" -type f -maxdepth 1 \
      -exec sed -i.bak "s|\(${MODULE_NAME}.git//.*\)\?ref=.*|\1\"|g" {} \; \
      -exec sed -i.bak "s|\(${MODULE_NAME}.git//.*\)\"|\1?ref=${MODULE_VERSION}\"|g" {} \; \
      -exec rm {}.bak \;
    terraform fmt
    cd "${TOP_LEVEL}" || (printf "\nDirectory %s does not exist\n" "${TOP_LEVEL}" && exit 1)
  done
}

envs=("qa" "prod")

for env in "${envs[@]}"; do
  update_module_versions "${env}"
done
