#!/usr/bin/env bash
# ============================================================
# Gitea 사용자 등록 스크립트
# 사용법: ./scripts/gitea-create-user.sh <username> <email> <password>
# 환경변수: GITEA_URL, GITEA_ADMIN_USER, GITEA_ADMIN_PASS
# ============================================================
set -euo pipefail

# ---------- 색상 ----------
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "${GREEN}[OK]${NC} $1"; }
fail() { echo -e "${RED}[FAIL]${NC} $1"; exit 1; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

# ---------- 인자 ----------
if [ $# -lt 3 ]; then
    echo "사용법: $0 <username> <email> <password>"
    echo ""
    echo "예시:"
    echo "  $0 hong hong@company.com P@ssw0rd123"
    echo "  $0 kim kim@company.com P@ssw0rd123"
    echo ""
    echo "환경변수 (선택):"
    echo "  GITEA_URL         Gitea 서버 URL (기본: https://git.wbx.kr)"
    echo "  GITEA_ADMIN_USER  관리자 계정 (기본: accura)"
    echo "  GITEA_ADMIN_PASS  관리자 비밀번호"
    exit 1
fi

USERNAME="$1"
EMAIL="$2"
PASSWORD="$3"

GITEA_URL="${GITEA_URL:-https://git.wbx.kr}"
GITEA_ADMIN_USER="${GITEA_ADMIN_USER:-accura}"

if [ -z "${GITEA_ADMIN_PASS:-}" ]; then
    read -s -p "Gitea 관리자(${GITEA_ADMIN_USER}) 비밀번호: " GITEA_ADMIN_PASS
    echo ""
fi

API="${GITEA_URL}/api/v1"

# ---------- 서버 연결 확인 ----------
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${API}/version" 2>/dev/null || echo "000")
if [ "$HTTP_CODE" != "200" ]; then
    fail "Gitea 서버 연결 실패: ${GITEA_URL} (HTTP ${HTTP_CODE})"
fi

# ---------- 중복 확인 ----------
EXISTS=$(curl -s -o /dev/null -w "%{http_code}" \
    -u "${GITEA_ADMIN_USER}:${GITEA_ADMIN_PASS}" \
    "${API}/users/${USERNAME}" 2>/dev/null)

if [ "$EXISTS" = "200" ]; then
    warn "사용자 '${USERNAME}'이 이미 존재합니다."
    exit 0
fi

# ---------- 사용자 생성 ----------
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X POST "${API}/admin/users" \
    -u "${GITEA_ADMIN_USER}:${GITEA_ADMIN_PASS}" \
    -H "Content-Type: application/json" \
    -d "{
        \"username\": \"${USERNAME}\",
        \"email\": \"${EMAIL}\",
        \"password\": \"${PASSWORD}\",
        \"must_change_password\": true,
        \"visibility\": \"public\"
    }" 2>/dev/null)

HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')

if [ "$HTTP_CODE" = "201" ]; then
    ok "사용자 생성 완료: ${USERNAME} (${EMAIL})"
    echo "  → ${GITEA_URL}/${USERNAME}"
    echo "  → 첫 로그인 시 비밀번호 변경 필요"
else
    fail "사용자 생성 실패 (HTTP ${HTTP_CODE}): ${BODY}"
fi
