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

emit_env=false
ROOT="$(
  git rev-parse --show-toplevel 2>/dev/null || {
    cd "$(dirname "${BASH_SOURCE[0]}")/../.."
    pwd
  }
)"
runtime_dir="${BURROW_GCP_KMS_PKCS11_RUNTIME_DIR:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/burrow-google-kms-pkcs11-runtime}"
config_file="${BURROW_GCP_KMS_PKCS11_CONFIG:-${KMS_PKCS11_CONFIG:-}}"
config_yaml="${BURROW_GCP_KMS_PKCS11_CONFIG_YAML:-}"
key_ring="${BURROW_GCP_KMS_KEY_RING:-${GOOGLE_KMS_KEY_RING:-projects/${GOOGLE_CLOUD_PROJECT:-project-88c23ce9-918a-470a-b33}/locations/${BURROW_KMS_LOCATION:-global}/keyRings/${BURROW_KMS_KEYRING:-burrow-identity}}}"
token_label="${BURROW_GCP_KMS_PKCS11_TOKEN_LABEL:-${BURROW_PKCS11_TOKEN_LABEL:-burrow-release}}"

usage() {
  cat <<'EOF'
Usage: Scripts/release/google-kms-pkcs11-materialize.sh [--emit-env]

Materializes optional Google KMS PKCS#11 config YAML into a runner-local file
and emits environment variables consumed by the Apple release signer.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --emit-env)
      emit_env=true
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "error: unknown argument $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

write_config_file() {
  local path="$1"
  local value="$2"
  mkdir -p "$(dirname "$path")"
  printf '%s\n' "$value" >"$path"
  chmod 600 "$path"
}

resolve_config_path() {
  local path="$1"
  if [[ -z "$path" ]]; then
    return 1
  fi
  if [[ "$path" != /* ]]; then
    path="$ROOT/$path"
  fi
  printf '%s\n' "$path"
}

env_lines=()
if [[ -z "$config_file" && -n "$config_yaml" ]]; then
  config_file="$runtime_dir/pkcs11-config.yaml"
  write_config_file "$config_file" "$config_yaml"
fi

if [[ -z "$config_file" && -n "$key_ring" ]]; then
  config_file="$runtime_dir/pkcs11-config.yaml"
  write_config_file "$config_file" "---
tokens:
  - key_ring: \"${key_ring}\"
    label: \"${token_label}\""
fi

if [[ -n "$config_file" ]]; then
  config_file="$(resolve_config_path "$config_file")"
  if [[ ! -s "$config_file" ]]; then
    echo "error: Google KMS PKCS#11 config is missing or empty: $config_file" >&2
    exit 1
  fi
  env_lines+=("BURROW_GCP_KMS_PKCS11_CONFIG=$config_file")
  env_lines+=("KMS_PKCS11_CONFIG=$config_file")
fi

if [[ "${#env_lines[@]}" -gt 0 && -n "${GITHUB_ENV:-}" ]]; then
  printf '%s\n' "${env_lines[@]}" >>"$GITHUB_ENV"
fi

if [[ "$emit_env" == "true" && "${#env_lines[@]}" -gt 0 ]]; then
  printf 'export %q\n' "${env_lines[@]}"
fi
