#!/usr/bin/env bash
# Crée le dépôt privé, la branche develop et protège main.
# Prérequis : curl, jq. Variables : GITEA_URL, GITEA_TOKEN, REPO_OWNER, REPO_NAME.
set -Eeuo pipefail

: "${GITEA_URL:?GITEA_URL est obligatoire (ex: https://git.mairie-grimaud.fr)}"
: "${GITEA_TOKEN:?GITEA_TOKEN est obligatoire (jeton avec droits de création)}"
: "${REPO_OWNER:?REPO_OWNER est obligatoire (ex: thor)}"
: "${REPO_NAME:?REPO_NAME est obligatoire (ex: printmanager)}"

command -v curl >/dev/null 2>&1 || { echo "curl introuvable" >&2; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq introuvable" >&2; exit 1; }

API="${GITEA_URL%/}/api/v1"
AUTH=(-H "Authorization: token ${GITEA_TOKEN}" -H "Content-Type: application/json")

log() { printf '[gitea] %s\n' "$*"; }

create_repo() {
    local endpoint="$1"
    local payload
    payload="$(jq -n --arg name "$REPO_NAME" '{
        name: $name,
        private: true,
        auto_init: false,
        default_branch: "main",
        has_issues: true,
        has_wiki: false,
        has_projects: false
    }')"

    local code
    code="$(curl -sS -o /tmp/gitea_repo_create.json -w '%{http_code}' \
        -X POST "${API}${endpoint}" "${AUTH[@]}" -d "$payload")"

    case "$code" in
        201) log "Dépôt privé créé : ${REPO_OWNER}/${REPO_NAME}" ; return 0 ;;
        409) log "Dépôt déjà existant : ${REPO_OWNER}/${REPO_NAME}" ; return 0 ;;
        403|404) return 1 ;;
        *) log "Réponse inattendue (${code}) : $(cat /tmp/gitea_repo_create.json)" ; return 1 ;;
    esac
}

if ! create_repo "/orgs/${REPO_OWNER}/repos"; then
    log "Création via l'organisation impossible, tentative via le compte utilisateur..."
    create_repo "/user/repos" || {
        log "Création du dépôt impossible. Vérifiez les droits du jeton."
        exit 1
    }
fi

log "Création de la branche develop..."
code="$(curl -sS -o /tmp/gitea_branch.json -w '%{http_code}' \
    -X POST "${API}/repos/${REPO_OWNER}/${REPO_NAME}/branches" "${AUTH[@]}" \
    -d '{"new_branch_name":"develop","old_branch_name":"main"}')"
case "$code" in
    201|409) log "Branche develop disponible." ;;
    *) log "Création de develop ignorée (${code})." ;;
esac

log "Protection de main..."
protection="$(jq -n '{
    branch_name: "main",
    enable_push: false,
    enable_push_whitelist: false,
    enable_merge_whitelist: false,
    required_approvals: 1,
    enable_status_check: true,
    status_check_contexts: ["tests"],
    block_on_rejected_reviews: true,
    block_on_official_review_requests: true,
    block_on_outdated_branch: true,
    dismiss_stale_approvals: true,
    require_signed_commits: false
}')"

code="$(curl -sS -o /tmp/gitea_protection.json -w '%{http_code}' \
    -X POST "${API}/repos/${REPO_OWNER}/${REPO_NAME}/branch_protections" "${AUTH[@]}" \
    -d "$protection")"
case "$code" in
    201) log "Branche main protégée (1 approbation + statut tests)." ;;
    409) log "Protection de main déjà en place." ;;
    *) log "Protection à configurer manuellement (${code}) : $(cat /tmp/gitea_protection.json)" ;;
esac

log "Terminé. Poussez main puis develop, et vérifiez les règles dans Gitea."
