set -euo pipefail
umask 077
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")"
intent_hash="$(jq -er '.intentHash' <<<"$intent")"
[[ "$repository" == https://github.com/iacstack/iac-stack-controller.git ]]
[[ "$module" == website/static/examples/quickstart/module ]]
[[ "$stack" =~ ^consumer-(auto|manual|deny)$ ]]
[[ "$operation" == apply || "$operation" == destroy ]]
[[ "$IAC_ENGINE" == tofu || "$IAC_ENGINE" == terraform ]]
binding="kind:iacstack-quickstart/$stack"
existing="$(jq -r '.binding // empty' <<<"$intent")"
[[ -z "$existing" || "$existing" == "$binding" ]]
pinned="$(jq -r '.pinnedReference // empty' <<<"$intent")"
export TF_VAR_stack_name="$stack"
export TF_VAR_message="$(jq -er '.intent.inputs.message' <<<"$intent")"
plan_args=()
if [[ "$operation" == destroy ]]; then plan_args+=(-destroy); fi
token() {
  printf '%s\n' "$(sha256sum /workspace/change.plan | cut -d ' ' -f1)" "$revision" "$binding" "$intent_hash" "$IAC_ENGINE" | sha256sum | cut -d ' ' -f1
}
cd "/workspace/source/$module"
revision="$(git -C /workspace/source rev-parse HEAD)"
[[ -z "$pinned" || "$revision" == "$pinned" ]]
[[ "$(token)" == "$TOKEN" ]]
iacstack authorization claim --token "$TOKEN" --timeout 30s
"$IAC_ENGINE" apply -input=false /workspace/change.plan
"$IAC_ENGINE" plan -input=false -detailed-exitcode "${plan_args[@]}"
iacstack result --outcome Verified
