#!/usr/bin/env sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
INFRA_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
ENV_FILE="$INFRA_DIR/.env"

if [ -f "$ENV_FILE" ]; then
  echo "Refusing to overwrite existing $ENV_FILE" >&2
  exit 1
fi

rand() {
  openssl rand -base64 "$1" | tr -d '\n'
}

cat > "$ENV_FILE" <<EOF
# domains
NODEDC_ENV=local
AUTH_DOMAIN=auth.local.nodedc
LAUNCHER_DOMAIN=launcher.local.nodedc
TASK_DOMAIN=task.local.nodedc

# proxy
PLATFORM_HTTP_PORT=80
PLATFORM_PROXY_IMAGE=nodedc/plane-proxy:ru
LOCAL_LAUNCHER_UPSTREAM=host.docker.internal:5173
LOCAL_TASK_MANAGER_UPSTREAM=host.docker.internal:8090

# authentik image
AUTHENTIK_IMAGE=ghcr.io/goauthentik/server
AUTHENTIK_TAG=2026.2.2

# authentik database
PG_DB=authentik
PG_USER=authentik
PG_PASS=$(rand 36)

# authentik core
AUTHENTIK_SECRET_KEY=$(rand 60)
AUTHENTIK_ERROR_REPORTING__ENABLED=false
AUTHENTIK_BOOTSTRAP_EMAIL=admin@nodedc.local
AUTHENTIK_BOOTSTRAP_PASSWORD=$(rand 36)
AUTHENTIK_BOOTSTRAP_TOKEN=$(rand 36)

# launcher oidc
LAUNCHER_OIDC_ISSUER=http://auth.local.nodedc/application/o/launcher/
LAUNCHER_OIDC_CLIENT_ID=nodedc-launcher
LAUNCHER_OIDC_CLIENT_SECRET=$(openssl rand -hex 48 | tr -d '\n')
LAUNCHER_OIDC_REDIRECT_URI=http://launcher.local.nodedc/auth/callback

# plane oidc
PLANE_OIDC_ISSUER=http://auth.local.nodedc/application/o/task-manager/
PLANE_OIDC_CLIENT_ID=nodedc-task-manager
PLANE_OIDC_CLIENT_SECRET=$(openssl rand -hex 48 | tr -d '\n')
PLANE_OIDC_REDIRECT_URI=http://task.local.nodedc/auth/oidc/callback

# security
SESSION_SECRET=$(rand 48)
NODEDC_INTERNAL_ACCESS_TOKEN=$(openssl rand -hex 48 | tr -d '\n')
COOKIE_DOMAIN=.local.nodedc
COOKIE_SECURE=false

# AI Workspace shared registry and Hub.
# Generated local env may use the deployed AI Hub only as a relay for remote
# Codex workers. Launcher/Engine/Ops/Auth downstream URLs must remain local.
# For Tailscale/ngrok-style relay URLs, set NODEDC_ENV=tunnel-local-e2e deliberately.
AI_WORKSPACE_PG_DB=nodedc_ai_workspace
AI_WORKSPACE_PG_USER=nodedc_ai_workspace
AI_WORKSPACE_PG_PASS=$(rand 36)
AI_WORKSPACE_ASSISTANT_TOKEN=$(openssl rand -hex 48 | tr -d '\n')
AI_WORKSPACE_OPS_ENTITLEMENT_URL=http://host.docker.internal:4100/api/internal/v1/ai-workspace/entitlements
AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN=replace-with-ops-agent-gateway-internal-token
AI_WORKSPACE_OPS_ENTITLEMENT_REQUIRED=false
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ENABLED=true
AI_WORKSPACE_ASSISTANT_ACTION_RELAY_ID=local-dev
AI_WORKSPACE_HUB_TOKEN=$(openssl rand -hex 48 | tr -d '\n')
AI_WORKSPACE_HUB_HOST_BIND=127.0.0.1:18081
AI_WORKSPACE_HUB_PUBLIC_URL=wss://ai-hub.nodedc.ru/api/ai-workspace/hub
AI_WORKSPACE_HUB_INTERNAL_URL=https://ai-hub.nodedc.ru
AI_WORKSPACE_HUB_FALLBACK_URLS=
EOF

chmod 600 "$ENV_FILE"
echo "Created $ENV_FILE"
echo "Open $ENV_FILE to read the generated local akadmin bootstrap credentials."
