#!/bin/bash

set -e -o pipefail

if [[ -n "${GITHUB_SSH_KEY}" ]]; then
  echo "${GITHUB_SSH_KEY}" > ~/.ssh/id_rsa
else
  cp /run/secrets/GITHUB_SSH_KEY_FILE ~/.ssh/id_rsa
fi

chmod 600 ~/.ssh/id_rsa

cd terraform
tfswitch -b "${BIN_DIR}/terraform"
terraform init
terraform state pull > terraform.tfstate

# Find all resources where the provider is located within a module and replace with equivalent provider at the project root
# Also increment the serial number, which is required to push the modified state file
jq -r '
(.resources |= map(.provider |= (select(test("module\\..*\\[\\\"registry.terraform.io/hashicorp/aws\"\\]")) |= "provider[\"registry.terraform.io/hashicorp/aws\"]"))) |
(.resources |= map(.provider |= (select(test("module\\..*\\[\\\"registry.terraform.io/datadog/datadog\"\\]")) |= "provider[\"registry.terraform.io/datadog/datadog\"]"))) |
(.resources |= map(.provider |= (select(test("module\\..*\\[\\\"registry.terraform.io/jianyuan/sentry\"\\]")) |= "provider[\"registry.terraform.io/jianyuan/sentry\"]"))) |
(.serial |= (. + 1))
' < terraform.tfstate > terraform.tfstate.converted

if [ "${DRY_RUN}" -ne 1 ]; then
  echo 'Pushing converted state file'
  terraform state push terraform.tfstate.converted
else
  echo 'Converted state file has been saved to terraform.tfstate.converted'
fi
