#!/usr/bin/env bash
# drone — INSTALL-TIME gitea SCM wiring hook (rcust P2b).
#
# Runs AFTER `abra app new` + EXTRA_ENV + `abra app secret generate`, BEFORE `abra app deploy`.
# Reads the gitea dep creds from $CCCI_DEPS_FILE (written by the orchestrator's dep provisioning
# step), then:
#   1. Switches drone to gitea SCM mode (COMPOSE_FILE includes compose.gitea.yml).
#   2. Sets GITEA_CLIENT_ID + GITEA_DOMAIN in drone's .env.
#   3. Sets CLIENT_SECRET_VERSION and inserts the gitea OAuth2 client_secret as a swarm secret.
#   4. Sets DRONE_USER_CREATE so the gitea ci_admin becomes drone's first admin on login.
#
# If the deps file is absent or has no gitea entry, drone is still deployed (without SCM wiring);
# the custom/test_scm_configured.py test then FAILS, which is the correct signal.
#
# Env supplied by the harness:
#   CCCI_APP_DOMAIN — the per-run drone app domain
#   CCCI_APP_ENV    — path to the app's .env
#   CCCI_DEPS_FILE  — JSON {gitea: {domain, admin_user, admin_password, client_id, client_secret}}
set -euo pipefail

: "${CCCI_APP_DOMAIN:?missing}"
ENV_PATH="${CCCI_APP_ENV:?missing}"

if [ -z "${CCCI_DEPS_FILE:-}" ] || [ ! -s "${CCCI_DEPS_FILE}" ]; then
  echo "  drone install_steps: no deps file — deploying drone WITHOUT gitea SCM wiring"
  exit 0
fi

GITEA_DOMAIN=$(jq -r '.gitea.domain        // empty' "$CCCI_DEPS_FILE")
GITEA_CLIENT_ID=$(jq -r '.gitea.client_id  // empty' "$CCCI_DEPS_FILE")
GITEA_SECRET=$(jq -r '.gitea.client_secret // empty' "$CCCI_DEPS_FILE")
GITEA_ADMIN=$(jq -r '.gitea.admin_user     // empty' "$CCCI_DEPS_FILE")

if [ -z "$GITEA_DOMAIN" ] || [ -z "$GITEA_CLIENT_ID" ] || [ -z "$GITEA_SECRET" ]; then
  echo "  drone install_steps: deps file missing gitea domain/client_id/secret — no SCM wiring"
  exit 0
fi

echo "  drone install_steps: wiring gitea SCM (domain=${GITEA_DOMAIN}, client_id=${GITEA_CLIENT_ID})"

# Helper: write or replace a key=value line in the drone .env file.
write_env() {
  local key="$1" val="$2"
  sed -i "/^\s*#\?\s*${key}=/d" "$ENV_PATH"
  [ -z "$(tail -c1 "$ENV_PATH" 2>/dev/null)" ] || printf '\n' >>"$ENV_PATH"
  printf '%s=%s\n' "$key" "$val" >>"$ENV_PATH"
}

# 1. Switch COMPOSE_FILE to include the gitea overlay (activates DRONE_GITEA_CLIENT_ID +
#    DRONE_GITEA_SERVER env and the client_secret swarm secret).
write_env COMPOSE_FILE "compose.yml:compose.gitea.yml"

# 2. Wire gitea identity into drone's .env.
write_env GITEA_CLIENT_ID "$GITEA_CLIENT_ID"
write_env GITEA_DOMAIN "$GITEA_DOMAIN"

# 3. Insert the gitea OAuth2 client_secret as a swarm secret at version v1.
#    The secret does not exist yet (abra secret generate only creates secrets declared in the
#    active COMPOSE_FILE; we just switched to compose.gitea.yml which adds client_secret).
write_env CLIENT_SECRET_VERSION "v1"
INSERT_LOG=$(abra app secret insert "$CCCI_APP_DOMAIN" client_secret v1 "$GITEA_SECRET" --no-input -C -o 2>&1) ||
  INSERT_LOG=$(script -qec "abra app secret insert $CCCI_APP_DOMAIN client_secret v1 $GITEA_SECRET --no-input -C -o" /dev/null 2>&1) ||
  {
    echo "  drone install_steps: abra app secret insert client_secret@v1 failed: $INSERT_LOG"
    exit 1
  }
echo "  drone install_steps: client_secret inserted at v1"

# 4. DRONE_USER_CREATE: when ci_admin first logs in via gitea OAuth, drone promotes them to admin.
#    Uses the gitea admin username from the dep provisioning step.
ADMIN_USER="${GITEA_ADMIN:-ci_admin}"
write_env DRONE_USER_CREATE "username:${ADMIN_USER},admin:true"

echo "  drone install_steps: gitea SCM wired (DRONE_USER_CREATE=username:${ADMIN_USER},admin:true)"
