#!/bin/bash
# ==============================================================
# Gitea 웹훅 자동 등록 스크립트
# ==============================================================
# Gitea 저장소에 Jenkins 빌드 트리거 웹훅을 등록합니다.
# Gitea PR 이벤트 → Jenkins 파이프라인 자동 실행
#
# 사용법:
#   bash cicd/scripts/notify/gitea_webhook.sh
#   JENKINS_URL=http://jenkins:8080 bash gitea_webhook.sh
# ==============================================================

set -euo pipefail

GITEA_BASE="${GITEA_BASE_URL:-http://localhost:3000}"
GITEA_ORG="${GITEA_ORG:-guardia}"
GITEA_REPO="${GITEA_REPO:-GUARDiA}"
GITEA_ADMIN="${GITEA_ADMIN:-gitadmin}"
GITEA_ADMIN_PW="${GITEA_ADMIN_PW:-Gitea@guardia!}"
JENKINS_URL="${JENKINS_URL:-http://localhost:8080}"
JENKINS_USER="${JENKINS_USER:-admin}"
JENKINS_TOKEN="${JENKINS_TOKEN:-}"

API="${GITEA_BASE}/api/v1"
AUTH="Authorization: Basic $(echo -n "${GITEA_ADMIN}:${GITEA_ADMIN_PW}" | base64)"

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "${GREEN}[OK]${NC}  $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
info() { echo -e "      $*"; }

echo "=================================================="
echo "  Gitea 웹훅 등록"
echo "  저장소: ${GITEA_BASE}/${GITEA_ORG}/${GITEA_REPO}"
echo "  Jenkins: ${JENKINS_URL}"
echo "=================================================="

# ── Jenkins Webhook URL ──────────────────────────────────────
# Jenkins Generic Webhook Trigger 플러그인 활용
WEBHOOK_TOKEN="${WEBHOOK_TOKEN:-guardia-jenkins-$(date +%s | md5sum | head -c 8)}"
WEBHOOK_URL="${JENKINS_URL}/generic-webhook-trigger/invoke?token=${WEBHOOK_TOKEN}"

# API 토큰이 있으면 Basic Auth 포함
if [[ -n "$JENKINS_TOKEN" ]]; then
  WEBHOOK_URL="${JENKINS_URL%/}/generic-webhook-trigger/invoke?token=${WEBHOOK_TOKEN}"
fi

# ── 기존 웹훅 삭제 (중복 방지) ──────────────────────────────
info "기존 Jenkins 웹훅 정리..."
EXISTING=$(curl -sf "$API/repos/${GITEA_ORG}/${GITEA_REPO}/hooks" \
  -H "$AUTH" 2>/dev/null | python3 -c "
import sys, json
hooks = json.load(sys.stdin)
ids = [str(h['id']) for h in hooks if 'jenkins' in str(h.get('config',{})).lower() or 'generic-webhook' in str(h.get('config',{})).lower()]
print(' '.join(ids))
" 2>/dev/null || echo "")

for hook_id in $EXISTING; do
  curl -sf -X DELETE "$API/repos/${GITEA_ORG}/${GITEA_REPO}/hooks/${hook_id}" \
    -H "$AUTH" -o /dev/null 2>/dev/null
  info "기존 웹훅 삭제: ID=$hook_id"
done

# ── 웹훅 등록 ────────────────────────────────────────────────
info "Jenkins 웹훅 등록 중..."
RESP=$(curl -sf -X POST "$API/repos/${GITEA_ORG}/${GITEA_REPO}/hooks" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d "{
    \"type\":\"gitea\",
    \"config\":{
      \"url\":\"${WEBHOOK_URL}\",
      \"content_type\":\"json\",
      \"secret\":\"${WEBHOOK_TOKEN}\"
    },
    \"events\":[\"push\",\"pull_request\",\"pull_request_review\"],
    \"active\":true,
    \"branch_filter\":\"*\"
  }" 2>/dev/null)

HOOK_ID=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null || echo "")
if [[ -n "$HOOK_ID" ]]; then
  ok "웹훅 등록 완료 (ID: $HOOK_ID)"
else
  warn "웹훅 등록 실패 — 수동 등록 필요"
  info "  Gitea → 저장소 → Settings → Webhooks → Add Webhook"
  info "  URL: $WEBHOOK_URL"
fi

# ── PR 이벤트 웹훅 설정 (PR 오픈 시 Jenkins 빌드) ────────────
info "PR 이벤트 웹훅 등록..."
PR_RESP=$(curl -sf -X POST "$API/repos/${GITEA_ORG}/${GITEA_REPO}/hooks" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d "{
    \"type\":\"gitea\",
    \"config\":{
      \"url\":\"${JENKINS_URL}/job/guardia-pr/build?token=${WEBHOOK_TOKEN}\",
      \"content_type\":\"json\"
    },
    \"events\":[\"pull_request\"],
    \"active\":true
  }" 2>/dev/null)

PR_HOOK_ID=$(echo "$PR_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null || echo "")
[[ -n "$PR_HOOK_ID" ]] && ok "PR 트리거 웹훅 등록 (ID: $PR_HOOK_ID)" || warn "PR 웹훅 등록 실패"

# ── develop → main PR 자동화 설명 ────────────────────────────
echo ""
echo "=================================================="
ok "Gitea 웹훅 설정 완료!"
echo ""
info "=== CI/CD 트리거 흐름 ==="
info "  1. 개발자가 feature/이름/기능 브랜치에 push"
info "  2. Gitea 웹훅 → Jenkins Generic Webhook Trigger"
info "  3. Jenkins가 해당 브랜치 빌드·테스트"
info "  4. PR (feature → develop) 생성"
info "  5. 리뷰어 승인 후 develop 자동 병합"
info "  6. develop → main PR → 관리자 승인 → 운영 배포"
echo ""
info "웹훅 토큰: $WEBHOOK_TOKEN"
info "Jenkins 웹훅 URL: $WEBHOOK_URL"
echo "=================================================="
