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

TARGET_ROOT="${1:-.}"
BLACKSHIELD_POLICY_IMAGE="${BLACKSHIELD_POLICY_IMAGE:-public.ecr.aws/blackshield-security/policy-client:1.0.0}"

replace_literal() {
  local file_path="$1"
  local placeholder="$2"
  local replacement="$3"
  local tmp_file="${file_path}.tmp.$$"

  sed "s|${placeholder}|${replacement}|g" "$file_path" > "$tmp_file"
  mv "$tmp_file" "$file_path"
}

mkdir -p "$TARGET_ROOT/.github/workflows"
cat > "$TARGET_ROOT/.github/workflows/deploy-guardrails.yml" <<'EOF'
name: Deploy Guardrails

on:
  workflow_dispatch:
    inputs:
      service_id:
        description: "Service identifier used by BlackShield policy evaluation"
        required: true
        default: "payment-gateway"
      target_environment:
        description: "Deployment environment"
        required: true
        default: "prod"

jobs:
  deploy-guardrails:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Evaluate hosted deploy guardrails
        run: |
          docker run --rm \
            -e BLACKSHIELD_API_URL="${{ vars.BLACKSHIELD_API_URL }}" \
            -e BLACKSHIELD_API_KEY="${{ secrets.BLACKSHIELD_API_KEY }}" \
            -e POLICY_SERVICE_ID="${{ inputs.service_id }}" \
            -e POLICY_TARGET_ENVIRONMENT="${{ inputs.target_environment }}" \
            -e POLICY_REPOSITORY="${{ github.repository }}" \
            -e POLICY_ARTIFACT="ghcr.io/acme/${{ inputs.service_id }}:${{ github.sha }}" \
            -e POLICY_COMMIT_SHA="${{ github.sha }}" \
            -e POLICY_BRANCH="${{ github.ref_name }}" \
            -e POLICY_ACTOR="${{ github.actor }}" \
            -e POLICY_DEPLOYMENT_TARGET="production-cluster-a" \
            -e POLICY_CONTEXT_JSON='{"reviewer":"${{ github.actor }}","pipeline":"deploy-production"}' \
            __BLACKSHIELD_POLICY_IMAGE__
EOF

replace_literal \
  "$TARGET_ROOT/.github/workflows/deploy-guardrails.yml" \
  "__BLACKSHIELD_POLICY_IMAGE__" \
  "$BLACKSHIELD_POLICY_IMAGE"

printf "Wrote source bundle files:\n"
printf "  - %s\n" "$TARGET_ROOT/.github/workflows/deploy-guardrails.yml"
