#!/bin/sh
set -eu
umask 077

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
target="$ROOT/.env.e2e"

if [ -f "$target" ]; then
  chmod 600 "$target"
  updated=false

  if ! grep -q '^TRAEFIK_RETRY_ATTEMPTS=' "$target"; then
    printf '\nTRAEFIK_RETRY_ATTEMPTS=3\n' >>"$target"
    updated=true
  fi

  if grep -q '^E2E_BASE_URL=http://proxy$' "$target"; then
    sed -i \
      -e 's|^E2E_BASE_URL=http://proxy$|E2E_BASE_URL=https://proxy|' \
      -e 's|^PHX_SCHEME=http$|PHX_SCHEME=https|' \
      -e 's|^PHX_URL_PORT=80$|PHX_URL_PORT=443|' \
      -e 's|^MAP_TILE_URL=http://proxy/|MAP_TILE_URL=https://proxy/|' \
      "$target"
    updated=true
  fi

  chmod 600 "$target"

  if [ "$updated" = true ]; then
    echo "Updated non-secret E2E transport inputs; existing secrets were preserved."
  else
    echo ".env.e2e already exists; no secret or experiment input was changed."
  fi

  exit 0
fi

postgres_password=$(openssl rand -hex 32)
secret_key_base=$(openssl rand -hex 64)
handover_secret=$(openssl rand -hex 64)
release_cookie=$(openssl rand -hex 64)
metrics_token=$(openssl rand -hex 32)
docker_socket_gid=$(stat -c '%g' /var/run/docker.sock)

cat >"$target" <<EOF
DEPLOYMENT_TARGET=compose
DEPLOYMENT_ENV=development
APP_TOPOLOGY=split
DATABASE_MODE=container
HTTP_PORT=0
MAILPIT_PORT=0
DOCKER_SOCKET_GID=$docker_socket_gid
TRAEFIK_TRUSTED_IPS=127.0.0.1/32
TRAEFIK_RETRY_ATTEMPTS=3
TRAEFIK_PROJECT_CONSTRAINT=generated-per-run
TRAEFIK_APP_NAME=generated-per-run
TRAEFIK_DOCKER_NETWORK=generated-per-run
TRAEFIK_ROUTER_RULE='PathPrefix(\`/\`)'
PHX_HOST=proxy
PHX_SCHEME=https
PHX_URL_PORT=443
MAP_TILE_URL=https://proxy/__e2e__/map-tile.png?z={z}&x={x}&y={y}
POSTGRES_DB=who_need_help_e2e
POSTGRES_USER=postgres
POSTGRES_PASSWORD=$postgres_password
DATABASE_URL=ecto://postgres:$postgres_password@db/who_need_help_e2e
WEB_POOL_SIZE=4
WORKER_POOL_SIZE=2
MIGRATE_POOL_SIZE=2
COMBINED_POOL_SIZE=4
OBAN_MAINTENANCE_CONCURRENCY=2
OBAN_PUSH_CONCURRENCY=1
WEB_REPLICAS=2
WORKER_REPLICAS=2
ERLANG_PORT_LIMIT=65536
SECRET_KEY_BASE=$secret_key_base
HANDOVER_SECRET=$handover_secret
RELEASE_COOKIE=$release_cookie
METRICS_TOKEN=$metrics_token
SMTP_RELAY=mailpit
SMTP_PORT=1025
SMTP_USERNAME=
SMTP_PASSWORD=
SMTP_AUTH=never
SMTP_TLS=never
SMTP_SSL=false
EMAIL_FROM_NAME="Who Need Help E2E"
EMAIL_FROM_ADDRESS=e2e@example.invalid
CODEX_SESSION_ID=local-e2e
RATE_LIMIT_POLICIES_JSON={}
GITHUB_OAUTH_CLIENT_ID=
GITHUB_OAUTH_CLIENT_SECRET=
GOOGLE_OAUTH_CLIENT_ID=
GOOGLE_OAUTH_CLIENT_SECRET=
E2E_BASE_URL=https://proxy
E2E_MAILPIT_URL=http://mailpit:8025
E2E_OUTPUT_DIR=$ROOT/output/e2e/generated-per-run
EOF

chmod 600 "$target"
echo "Generated .env.e2e with independent local secrets and mode 0600."
