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

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
INFRA_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
ROOT_DIR=$(CDPATH= cd -- "$INFRA_DIR/.." && pwd)
ENV_FILE="$INFRA_DIR/.env"
COMPOSE_FILE="$INFRA_DIR/docker-compose.dev.yml"
BOOTSTRAP_SCRIPT="$INFRA_DIR/authentik/bootstrap-dev.py"

if [ ! -f "$ENV_FILE" ]; then
  echo "Missing $ENV_FILE. Run infra/scripts/init-dev-env.sh first." >&2
  exit 1
fi

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

upsert_env() {
  key="$1"
  value="$2"
  python3 - "$ENV_FILE" "$key" "$value" <<'PY'
from pathlib import Path
from sys import argv

path = Path(argv[1])
key = argv[2]
value = argv[3]
lines = path.read_text().splitlines()
prefix = f"{key}="
for index, line in enumerate(lines):
    if line.startswith(prefix):
        lines[index] = f"{key}={value}"
        break
else:
    lines.append(f"{key}={value}")
path.write_text("\n".join(lines) + "\n")
PY
}

get_env() {
  key="$1"
  awk -F= -v key="$key" '$1 == key {print substr($0, length(key) + 2)}' "$ENV_FILE" | tail -n 1
}

ensure_env_value() {
  key="$1"
  fallback="$2"
  value=$(get_env "$key")
  if [ -z "$value" ]; then
    value="$fallback"
    upsert_env "$key" "$value"
  fi
}

ensure_env_value LAUNCHER_OIDC_CLIENT_ID nodedc-launcher
ensure_env_value PLANE_OIDC_CLIENT_ID nodedc-task-manager
ensure_env_value LAUNCHER_OIDC_CLIENT_SECRET "$(rand_hex 48)"
ensure_env_value PLANE_OIDC_CLIENT_SECRET "$(rand_hex 48)"
ensure_env_value NODEDC_INTERNAL_ACCESS_TOKEN "$(rand_hex 48)"
ensure_env_value LAUNCHER_OIDC_REDIRECT_URI http://launcher.local.nodedc/auth/callback
ensure_env_value PLANE_OIDC_REDIRECT_URI http://task.local.nodedc/auth/oidc/callback

set -a
. "$ENV_FILE"
set +a

cd "$ROOT_DIR"
docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" exec -T \
  -e AUTH_DOMAIN="${AUTH_DOMAIN:-auth.local.nodedc}" \
  -e NODEDC_BOOTSTRAP_ADMIN_EMAIL="${NODEDC_BOOTSTRAP_ADMIN_EMAIL:-}" \
  -e NODEDC_BOOTSTRAP_ADMIN_PASSWORD="${NODEDC_BOOTSTRAP_ADMIN_PASSWORD:-}" \
  -e LAUNCHER_OIDC_CLIENT_ID="$LAUNCHER_OIDC_CLIENT_ID" \
  -e LAUNCHER_OIDC_CLIENT_SECRET="$LAUNCHER_OIDC_CLIENT_SECRET" \
  -e LAUNCHER_OIDC_REDIRECT_URI="$LAUNCHER_OIDC_REDIRECT_URI" \
  -e PLANE_OIDC_CLIENT_ID="$PLANE_OIDC_CLIENT_ID" \
  -e PLANE_OIDC_CLIENT_SECRET="$PLANE_OIDC_CLIENT_SECRET" \
  -e PLANE_OIDC_REDIRECT_URI="$PLANE_OIDC_REDIRECT_URI" \
  authentik-server ak shell < "$BOOTSTRAP_SCRIPT"
