#!/usr/bin/env bash
# Maak SysOps Gitea-gebruiker aan (login: sysops) en geef write op backup-repo.
set -euo pipefail

GITEA_URL="${GITEA_URL:-http://127.0.0.1:3001}"
ADMIN_USER="${GITEA_ADMIN_USER:-aissa}"
ADMIN_PASS="${GITEA_ADMIN_PASS:-Foodlinkk#2026}"
SYSOPS_USER="${GITEA_SYSOPS_USER:-sysops}"
SYSOPS_PASS="${GITEA_SYSOPS_PASS:-Foodlinkk#SysOps2026}"
SYSOPS_EMAIL="${GITEA_SYSOPS_EMAIL:-sysops@foodlinkk.local}"
REPO_OWNER="${GITEA_REPO_OWNER:-aissa}"
REPO_NAME="${GITEA_REPO_NAME:-foodlinkk-command-center}"
CONTAINER="${GITEA_CONTAINER:-foodlinkk_gitea}"

echo "=== Gitea SysOps setup ($SYSOPS_USER) ==="

if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER}$"; then
  if ! docker exec "$CONTAINER" gitea admin user list 2>/dev/null | grep -q "^${SYSOPS_USER} "; then
    echo "Creating user $SYSOPS_USER..."
    docker exec "$CONTAINER" gitea admin user create \
      --username "$SYSOPS_USER" \
      --password "$SYSOPS_PASS" \
      --email "$SYSOPS_EMAIL" \
      --must-change-password=false 2>/dev/null || true
  else
    echo "User $SYSOPS_USER exists — updating password..."
    docker exec "$CONTAINER" gitea admin user change-password \
      --username "$SYSOPS_USER" \
      --password "$SYSOPS_PASS" 2>/dev/null || true
  fi
else
  echo "Gitea container not running — skip user create (will retry on deploy)"
fi

enc_pass() {
  python3 -c "import urllib.parse; print(urllib.parse.quote('''$1''', safe=''))"
}

SYSOPS_PASS_ENC=$(enc_pass "$SYSOPS_PASS")
AUTH=$(printf '%s:%s' "$ADMIN_USER" "$ADMIN_PASS" | base64 -w0 2>/dev/null || printf '%s:%s' "$ADMIN_USER" "$ADMIN_PASS" | base64)

HTTP_CODE=$(curl -sf -o /dev/null -w "%{http_code}" \
  -X PUT "${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/collaborators/${SYSOPS_USER}" \
  -H "Authorization: Basic ${AUTH}" \
  -H "Content-Type: application/json" \
  -d '{"permission":"write"}' 2>/dev/null || echo "000")

if [ "$HTTP_CODE" = "204" ] || [ "$HTTP_CODE" = "201" ]; then
  echo "Collaborator $SYSOPS_USER → write on ${REPO_OWNER}/${REPO_NAME}"
elif [ "$HTTP_CODE" = "422" ]; then
  echo "Collaborator already configured"
else
  echo "Note: collaborator API returned HTTP $HTTP_CODE (repo may not exist yet)"
fi

REMOTE="http://${SYSOPS_USER}:${SYSOPS_PASS_ENC}@gitea:3001/${REPO_OWNER}/${REPO_NAME}.git"
echo "GITEA_BACKUP_REMOTE=$REMOTE"
echo "=== SysOps kan pushen als $SYSOPS_USER ==="
