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

TARGET_ROOT="${1:-.}"
BLACKSHIELD_SITE_URL="${BLACKSHIELD_SITE_URL:-https://app.blackshield.chaplau.com}"
BLACKSHIELD_API_URL="${BLACKSHIELD_API_URL:-$BLACKSHIELD_SITE_URL}"
BLACKSHIELD_SECURITY_AGENT_IMAGE="${BLACKSHIELD_SECURITY_AGENT_IMAGE:-public.ecr.aws/blackshield-security/security-agent: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/deploy/security-agent"

cat > "$TARGET_ROOT/deploy/security-agent/docker-compose.security-agent.yml" <<'EOF'
services:
  security-agent:
    image: __BLACKSHIELD_SECURITY_AGENT_IMAGE__
    restart: unless-stopped
    env_file:
      - .env.security-agent
    working_dir: /workspace
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ../../:/workspace
EOF

replace_literal \
  "$TARGET_ROOT/deploy/security-agent/docker-compose.security-agent.yml" \
  "__BLACKSHIELD_SECURITY_AGENT_IMAGE__" \
  "$BLACKSHIELD_SECURITY_AGENT_IMAGE"

if [ ! -f "$TARGET_ROOT/deploy/security-agent/.env.security-agent" ]; then
cat > "$TARGET_ROOT/deploy/security-agent/.env.security-agent" <<EOF
BLACKSHIELD_API_URL=${BLACKSHIELD_API_URL}
BLACKSHIELD_API_KEY=sagent_xxxx
SECURITY_AGENT_MODEL=gpt-4o-mini
SECURITY_AGENT_PROVIDER=openai
SECURITY_AGENT_MAX_STEPS=8
SECURITY_AGENT_COMMAND_TIMEOUT_SECONDS=120
EOF
  printf 'Wrote deploy/security-agent/.env.security-agent\n'
else
  printf 'Preserved existing deploy/security-agent/.env.security-agent\n'
fi

cat > "$TARGET_ROOT/deploy/security-agent/.env.security-agent.example" <<EOF
BLACKSHIELD_API_URL=${BLACKSHIELD_API_URL}
BLACKSHIELD_API_KEY=sagent_xxxx
SECURITY_AGENT_MODEL=gpt-4o-mini
SECURITY_AGENT_PROVIDER=openai
SECURITY_AGENT_MAX_STEPS=8
SECURITY_AGENT_COMMAND_TIMEOUT_SECONDS=120
EOF

cat > "$TARGET_ROOT/deploy/security-agent/README.md" <<'EOF'
# Security Agent Bootstrap

1. Open `.env.security-agent` and replace `BLACKSHIELD_API_KEY` with the installation bootstrap key from the Agents console.
2. Adjust `BLACKSHIELD_API_URL`, model, or timeouts only if your tenant needs non-default runtime settings.
3. Start the runtime:

```bash
docker compose -f docker-compose.security-agent.yml up -d
```

The agent will bootstrap against `/api/v1/security-agents/agent/bootstrap`, poll
for assignments, and pause for approval before any mutating local or
platform-side action.

`.env.security-agent.example` is kept as a clean reference copy so you can diff
or restore the default bootstrap values later.
EOF

printf 'Wrote deploy/security-agent/docker-compose.security-agent.yml\n'
printf 'Wrote deploy/security-agent/.env.security-agent.example\n'
printf 'Wrote deploy/security-agent/README.md\n'
