#!/usr/bin/env bash
set -euo pipefail

terraform_version="1.15.8"
terraform_archive="terraform_${terraform_version}_linux_amd64.zip"
terraform_sha256="d25ce7b6902013ad905db3d2eab0be4cd905887fe88b81a6171b8d5503c31f3d"
install_dir="${HOME}/.local/bin"
profile_file="${HOME}/.profile"
# Keep HOME and PATH literal for the future login shell.
# shellcheck disable=SC2016
path_line='export PATH="$HOME/.local/bin:$PATH"'

compatible_terraform() {
  command -v terraform >/dev/null 2>&1 || return 1

  terraform version -json |
    python3 -c '
import json
import sys

major, minor, *_ = (
    int(part)
    for part in json.load(sys.stdin)["terraform_version"].split(".")
)
raise SystemExit(0 if major == 1 and minor >= 8 else 1)
'
}

if compatible_terraform; then
  echo "Compatible Terraform already available: $(terraform version -json | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"terraform_version\"])')"
  exit 0
fi

for command_name in curl python3 sha256sum unzip; do
  command -v "${command_name}" >/dev/null 2>&1 || {
    echo "Required command not found: ${command_name}" >&2
    exit 1
  }
done

if [[ "$(uname -s)" != "Linux" ]] || [[ "$(uname -m)" != "x86_64" ]]; then
  echo "This installer supports the Google Cloud Shell Linux x86_64 environment." >&2
  echo "Use the official HashiCorp installer on other systems." >&2
  exit 1
fi

work_dir="$(mktemp -d)"
cleanup() {
  rm -rf "${work_dir}"
}
trap cleanup EXIT

curl --fail --location --silent --show-error \
  "https://releases.hashicorp.com/terraform/${terraform_version}/${terraform_archive}" \
  --output "${work_dir}/${terraform_archive}"

printf '%s  %s\n' \
  "${terraform_sha256}" \
  "${work_dir}/${terraform_archive}" |
  sha256sum --check -

mkdir -p "${install_dir}"
unzip -q "${work_dir}/${terraform_archive}" -d "${work_dir}/terraform"
install -m 0755 "${work_dir}/terraform/terraform" "${install_dir}/terraform"

touch "${profile_file}"
if ! grep -Fqx "${path_line}" "${profile_file}"; then
  printf '\n%s\n' "${path_line}" >>"${profile_file}"
fi

export PATH="${install_dir}:${PATH}"
echo "Installed Terraform $(terraform version -json | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"terraform_version\"])')"
echo "Open a new Cloud Shell tab later to reload PATH from ${profile_file}."
