#!/usr/bin/env bash
# ============================================================
# Gitea 사용자 일괄 등록
# 사용법: ./scripts/gitea-bulk-create.sh users.csv
#
# CSV 형식 (헤더 없이):
#   username,email,password
#   hong,hong@company.com,P@ssw0rd123
#   kim,kim@company.com,P@ssw0rd123
# ============================================================
set -euo pipefail

if [ $# -lt 1 ]; then
    echo "사용법: $0 <users.csv>"
    echo ""
    echo "CSV 형식:"
    echo "  username,email,password"
    echo "  hong,hong@company.com,P@ssw0rd123"
    exit 1
fi

CSV_FILE="$1"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [ ! -f "$CSV_FILE" ]; then
    echo "파일을 찾을 수 없습니다: $CSV_FILE"
    exit 1
fi

COUNT=0
FAIL=0

while IFS=',' read -r username email password; do
    # 빈 줄, 주석 건너뜀
    [[ -z "$username" || "$username" =~ ^# ]] && continue

    # 공백 제거
    username=$(echo "$username" | xargs)
    email=$(echo "$email" | xargs)
    password=$(echo "$password" | xargs)

    echo "--- ${username} (${email}) ---"
    if "${SCRIPT_DIR}/gitea-create-user.sh" "$username" "$email" "$password"; then
        COUNT=$((COUNT + 1))
    else
        FAIL=$((FAIL + 1))
    fi
done < "$CSV_FILE"

echo ""
echo "완료: 성공 ${COUNT}건, 실패 ${FAIL}건"
