#!/usr/bin/env bash
# Render a deployment .env from the GitHub Actions secrets/variables contexts.
#
# The caller (a deploy workflow) sets SECRETS_JSON and VARS_JSON from toJSON(secrets)/toJSON(vars)
# and invokes this with the output path. Deploy-only infra (DEPLOY_* keys) and the injected
# github_token are excluded; every value is @json-escaped so it round-trips through the app's
# dotenv parser. Nothing is printed (values are secret). Shared by every deploy target.
set -euo pipefail

: "${SECRETS_JSON:?SECRETS_JSON not set}"
: "${VARS_JSON:?VARS_JSON not set}"
out="${1:-env.generated}"

{
  echo "# Auto-generated by the deploy workflow from GitHub Actions secrets/variables."
  echo "# Do not edit by hand - change values in the repo's Actions settings instead."
  jq -rn '
    (env.SECRETS_JSON | fromjson) + (env.VARS_JSON | fromjson)
    | to_entries[]
    | select(((.key | startswith("DEPLOY_")) or (.key == "github_token")) | not)
    | .key + "=" + (.value | @json)
  '
} > "$out"
