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

action=${1:-apply}
remote_config=${CONFIG_PATH}
local_config=${LOCAL_CONFIG_PATH}
env=$(yq '.env' "${local_config}")
location=$(yq '.location' "${local_config}")
dataplane_subscriptions_json=$(yq -ojson '.dataplaneSubscriptions' "${local_config}" | jq -c '.')
eks_oidc_issuer=$(yq '.baseK8s.oidcIssuer' "${local_config}")
ms_namespace=$(yq '.baseK8s.msNamespace' "${local_config}")
job_id=$(yq '.jobId' "${local_config}")
remote_output=$(yq '.outputPath' "${local_config}")
local_output=/tmp/output.yaml
ROOT=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
tf_directory="${ROOT}/modules"
tfstate_rg=$(yq '.terraformStateResourceGroup' "${local_config}")
tfstate_storage_account=$(yq '.terraformStateStorageAccount' "${local_config}")
tfstate_container=$(yq '.terraformStateContainer' "${local_config}")

set -x
module_path="global-service"
cd "${tf_directory}/${module_path}"
tfstate="${module_path}/${env}/tfstate.json"
terraform init -reconfigure -backend-config="resource_group_name=${tfstate_rg}" -backend-config="storage_account_name=${tfstate_storage_account}" -backend-config="container_name=${tfstate_container}" -backend-config="key=${tfstate}"
terraform apply -auto-approve -var="env=${env}" -var="location=${location}" -var="eks_oidc_issuer=${eks_oidc_issuer}" -var="ms_namespace=${ms_namespace}" -var="dataplane_subscriptions=${dataplane_subscriptions_json}"
