set -euo pipefail
case "$IAC_ENGINE" in tofu|terraform) ;; *) exit 2 ;; esac

intent="$(iacstack intent read)"
repository="$(jq -er '.intent.sourceRef.repository' <<<"$intent")"
module="$(jq -er '.intent.sourceRef.path' <<<"$intent")"
version="$(jq -er '.intent.sourceRef.version' <<<"$intent")"
stack="$(jq -er '.intent.stack' <<<"$intent")"
operation="$(jq -er '.intent.operation' <<<"$intent")"

[[ "$repository" == https://github.com/iacstack/iac-stack-controller.git ]]
[[ "$module" == website/static/examples/quickstart/module ]]
pinned="$(jq -r '.pinnedReference // empty' <<<"$intent")"
if [[ -n "$pinned" ]]; then
  [[ "$pinned" =~ ^[0-9a-f]{40}$ ]]
  ref="$pinned"
else
  ref="refs/heads/$version"
  git check-ref-format "$ref"
fi

git init -q /tmp/quickstart
git -C /tmp/quickstart fetch -q --depth=1 "$repository" "$ref"
git -C /tmp/quickstart checkout -q --detach FETCH_HEAD
revision="$(git -C /tmp/quickstart rev-parse HEAD)"
iacstack resolve --reference "$revision" --binding "kind:iacstack-quickstart/$stack"

cd "/tmp/quickstart/$module"
export TF_VAR_stack_name="$stack"
TF_VAR_message="$(jq -er '.intent.inputs.message' <<<"$intent")"
export TF_VAR_message

"$IAC_ENGINE" init -input=false "-backend-config=secret_suffix=$stack"
"$IAC_ENGINE" validate

plan_args=()
if [[ "$operation" == destroy ]]; then plan_args+=(-destroy); fi
status=0
"$IAC_ENGINE" plan -input=false -detailed-exitcode -out=/tmp/change.plan "${plan_args[@]}" || status=$?
if [[ "$status" == 0 && "$operation" == apply ]]; then
  iacstack result --outcome NoChanges
  exit 0
fi
[[ "$status" == 0 || "$status" == 2 ]]
"$IAC_ENGINE" apply -input=false /tmp/change.plan
"$IAC_ENGINE" plan -input=false -detailed-exitcode "${plan_args[@]}"
iacstack result --outcome Verified
