#!/usr/bin/env bash

###### script header ######

lib=$(realpath @@BASE_LIB@@) || exit 1
stat "${lib}" >> /dev/null || exit 1

# shellcheck source=../sh/lib.bash
if ! source "${lib}"; then
  echo "Error: could not find import"
  exit 1
fi

terraform=$(realpath @@TERRAFORM@@)
stat "${terraform}" >> /dev/null
mode="@@MODE@@"

cd "${BUILD_WORKSPACE_DIRECTORY}"

###### script body ######

readarray -t <<< "$(
  find "$(pwd)" -type f -name "*.tf" -exec dirname "{}" \; |
    sort -ud
)"
terraformPaths=("${MAPFILE[@]}")
terraformFormatModules=()
terraformLockModules=()
terraformCheckModules=()
pathPrefix="${terraformPaths[0]}"
for ((i = 1; i < ${#terraformPaths[@]}; i++)); do
  path="${terraformPaths[i]}"
  if [[ ${path} == "${pathPrefix}"* ]]; then
    continue
  fi
  terraformFormatModules+=("${pathPrefix}")
  terraformLockModules+=("${pathPrefix}")
  terraformCheckModules+=("${pathPrefix}")
  pathPrefix="${path}"
done

excludeDirs=(
  "build"
)

excludeLockDirs=(
  "build"
  "terraform-provider-constellation"
  "terraform/legacy-module"
)

excludeCheckDirs=(
  "build"
  "terraform-provider-constellation"
)

check() {
  echo "The following Terraform modules are excluded and won't be formatted:"
  for exclude in "${excludeDirs[@]}"; do
    for i in "${!terraformFormatModules[@]}"; do
      if [[ ${terraformFormatModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
        echo "  ${terraformFormatModules[i]}"
        unset 'terraformFormatModules[i]'
      fi
    done
  done

  echo "The following Terraform modules are excluded and their lockfiles won't be updated:"
  for exclude in "${excludeLockDirs[@]}"; do
    for i in "${!terraformLockModules[@]}"; do
      if [[ ${terraformLockModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
        echo "${terraformLockModules[i]}"
        unset 'terraformLockModules[i]'
      fi
    done
  done

  echo "The following Terraform modules are excluded and won't be checked:"
  for exclude in "${excludeCheckDirs[@]}"; do
    for i in "${!terraformCheckModules[@]}"; do
      if [[ ${terraformCheckModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
        echo "  ${terraformCheckModules[i]}"
        unset 'terraformCheckModules[i]'
      fi
    done
  done

  echo "The following Terraform modules are excluded and won't be locked:"
  for exclude in "${excludeLockDirs[@]}"; do
    for i in "${!terraformLockModules[@]}"; do
      if [[ ${terraformLockModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
        echo "  ${terraformLockModules[i]}"
        unset 'terraformLockModules[i]'
      fi
    done
  done

  echo "The following Terraform modules are excluded and won't be checked:"
  for exclude in "${excludeCheckDirs[@]}"; do
    for i in "${!terraformCheckModules[@]}"; do
      if [[ ${terraformCheckModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
        echo "  ${terraformCheckModules[i]}"
        unset 'terraformCheckModules[i]'
      fi
    done
  done

  case ${mode} in
  "check")
    echo "Checking validity and format of the following Terraform modules:"
    for script in "${terraformCheckModules[@]}"; do
      echo "  ${script}"
    done
    echo "This may take a minute..."
    for module in "${terraformCheckModules[@]}"; do
      ${terraform} -chdir="${module}" init > /dev/null
      ${terraform} -chdir="${module}" fmt -recursive > /dev/null
      ${terraform} -chdir="${module}" validate > /dev/null
      rm -rf "${module}/.terraform"
      echo "Deleting lock files in the following directories:" # init generates lockfiles which should only be generated in the generate mode.
      for dir in "${excludeLockDirs[@]}"; do
        if [[ -d ${dir} ]]; then
          find "${dir}" -name '*.lock.hcl' -type f -delete
        else
          echo "  Directory ${dir} does not exist, skipping"
        fi
      done
    done
    ;;

  "format")
    echo "Formatting the following Terraform modules:"
    for module in "${terraformFormatModules[@]}"; do
      echo "  ${module}"
      ${terraform} -chdir="${module}" fmt -recursive > /dev/null
    done
    ;;

  "generate")
    echo "Generating lock files for the following Terraform modules:"
    for script in "${terraformLockModules[@]}"; do
      echo "  ${script}"
    done
    echo "This may take 5-10 min..."
    for module in "${terraformLockModules[@]}"; do
      ${terraform} -chdir="${module}" init > /dev/null
      ${terraform} -chdir="${module}" providers lock -platform=linux_arm64 > /dev/null
      ${terraform} -chdir="${module}" providers lock -platform=linux_amd64 > /dev/null
      ${terraform} -chdir="${module}" providers lock -platform=darwin_arm64 > /dev/null
      ${terraform} -chdir="${module}" providers lock -platform=darwin_amd64 > /dev/null
      ${terraform} -chdir="${module}" providers lock -platform=windows_amd64 > /dev/null
      rm -rf "${module}/.terraform"
    done
    ;;

  *)
    echo "Error: unknown mode \"${mode}\""
    exit 1
    ;;
  esac
}

if test -v SILENT; then
  check > /dev/null
else
  check
fi
