#!/usr/bin/env bash
# Configura branch develop + proteção main (PR obrigatório) no Forgejo.
# Executar no CT130 com acesso à API Forgejo.
set -euo pipefail

FORGEJO_URL="${FORGEJO_URL:-http://10.10.10.130:3000}"
USER="${FORGEJO_USER:-roger}"
PASS="${FORGEJO_TOKEN:-805353}"
OWNER="${FORGEJO_OWNER:-ligbox}"
REPO="${FORGEJO_REPO:-ligbox-ops-platform}"
REPO_DIR="${REPO_DIR:-/opt/ligbox-spec-hub/repos/ligbox-ops-platform}"

auth() { echo -n "${USER}:${PASS}" | base64 -w0 2>/dev/null || echo -n "${USER}:${PASS}" | base64; }

api() {
  local method="$1" path="$2" data="${3:-}"
  if [[ -n "$data" ]]; then
    curl -sk -X "$method" -H "Authorization: Basic $(auth)" -H "Content-Type: application/json" \
      "${FORGEJO_URL}/api/v1${path}" -d "$data"
  else
    curl -sk -X "$method" -H "Authorization: Basic $(auth)" \
      "${FORGEJO_URL}/api/v1${path}"
  fi
}

echo "==> 1. Branch develop"
cd "$REPO_DIR"
git fetch origin
if git show-ref --verify --quiet refs/heads/develop; then
  git checkout develop
  git pull origin develop
else
  git checkout -b develop origin/main
fi
git push -u origin develop

echo "==> 2. Default branch = develop"
api PATCH "/repos/${OWNER}/${REPO}" '{"default_branch":"develop"}' | python3 -c "import sys,json; d=json.load(sys.stdin); print('default:', d.get('default_branch'))"

echo "==> 3. Proteção main (PR only)"
existing=$(api GET "/repos/${OWNER}/${REPO}/branch_protections" | python3 -c "import sys,json; print('main' in [x.get('branch_name') for x in json.load(sys.stdin)])")
if [[ "$existing" == "False" ]]; then
  api POST "/repos/${OWNER}/${REPO}/branch_protections" '{
    "branch_name":"main",
    "enable_push":false,
    "enable_push_whitelist":false,
    "required_approvals":0,
    "apply_to_admins":true
  }' | python3 -c "import sys,json; d=json.load(sys.stdin); print('protected:', d.get('branch_name'))"
else
  echo "main já protegida"
fi

echo "==> 4. Verificação"
api GET "/repos/${OWNER}/${REPO}/branches/main" | python3 -c "
import sys,json
d=json.load(sys.stdin)
print('main protected:', d.get('protected'))
print('can_push:', d.get('user_can_push'))
print('can_merge:', d.get('user_can_merge'))
"

echo ""
echo "OK — develop ativo, main só via PR"
echo "PR template: ${FORGEJO_URL/https:\/\//https://git.spec.ligbox.com.br/}/ligbox/${REPO}/compare/main...develop"
