#!/bin/bash

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NGINX_DIR="/data/training/nginx"
PASS=0
FAIL=0

# docker compose v1/v2 자동 감지
if command -v docker-compose &>/dev/null; then
    DOCKER_COMPOSE="docker-compose"
elif docker compose version &>/dev/null 2>&1; then
    DOCKER_COMPOSE="docker compose"
else
    DOCKER_COMPOSE=""
fi

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

ok()   { echo -e "${GREEN}[OK]${NC}   $1"; ((PASS++)); }
fail() { echo -e "${RED}[FAIL]${NC} $1"; ((FAIL++)); }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
section() { echo ""; echo "=== $1 ==="; }

# ──────────────────────────────────────────
section "디렉토리 확인"
# ──────────────────────────────────────────
for dir in \
    /data/training/request \
    /data/training/request/tmp \
    /data/training/response \
    /data/training/response/v6-cls-checkpoints \
    /data/training/tmp \
    "$NGINX_DIR" \
    "$NGINX_DIR/ssl" \
    "$NGINX_DIR/logs"; do
    if [ -d "$dir" ]; then
        ok "$dir"
    else
        fail "$dir 없음"
    fi
done

# ──────────────────────────────────────────
section "nginx 파일 확인"
# ──────────────────────────────────────────
for f in \
    "$NGINX_DIR/nginx.conf" \
    "$NGINX_DIR/docker-compose-nginx.yml" \
    "$NGINX_DIR/ssl/train-kamco.com.crt" \
    "$NGINX_DIR/ssl/train-kamco.com.key" \
    "$NGINX_DIR/ssl/openssl.cnf"; do
    if [ -f "$f" ]; then
        ok "$f"
    else
        fail "$f 없음"
    fi
done

# ──────────────────────────────────────────
section "파일 권한 확인"
# ──────────────────────────────────────────
SSL_DIR_PERM=$(stat -c "%a" "$NGINX_DIR/ssl" 2>/dev/null)
KEY_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.key" 2>/dev/null)
CRT_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.crt" 2>/dev/null)

[ "$SSL_DIR_PERM" = "700" ] && ok "ssl/ 권한 700" || fail "ssl/ 권한 오류 (현재: $SSL_DIR_PERM, 기대: 700)"
[ "$KEY_PERM" = "600" ]     && ok "train-kamco.com.key 권한 600" || fail "key 권한 오류 (현재: $KEY_PERM, 기대: 600)"
[ "$CRT_PERM" = "644" ]     && ok "train-kamco.com.crt 권한 644" || fail "crt 권한 오류 (현재: $CRT_PERM, 기대: 644)"

# ──────────────────────────────────────────
section "소유권 확인 (kcomu:kcomu)"
# ──────────────────────────────────────────
OWNER=$(stat -c "%U:%G" /data/training 2>/dev/null)
[ "$OWNER" = "kcomu:kcomu" ] && ok "/data/training 소유권 kcomu:kcomu" || fail "/data/training 소유권 오류 (현재: $OWNER)"

# ──────────────────────────────────────────
section "SSL 인증서 유효성"
# ──────────────────────────────────────────
if command -v openssl &>/dev/null && [ -f "$NGINX_DIR/ssl/train-kamco.com.crt" ]; then
    EXPIRY=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -enddate 2>/dev/null | cut -d= -f2)
    EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null)
    NOW_EPOCH=$(date +%s)
    if [ "$EXPIRY_EPOCH" -gt "$NOW_EPOCH" ]; then
        ok "인증서 유효 (만료: $EXPIRY)"
    else
        fail "인증서 만료됨 (만료: $EXPIRY)"
    fi

    SAN=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -text 2>/dev/null | grep -A1 "Subject Alternative Name" | tail -1)
    echo "    SAN: $SAN"
else
    warn "openssl 없음 또는 인증서 파일 없음 - 인증서 검증 스킵"
fi

# ──────────────────────────────────────────
section "Docker 확인"
# ──────────────────────────────────────────
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
    ok "Docker 실행 중"

    # Docker network
    if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
        ok "Docker network kamco-cds 존재"
    else
        fail "Docker network kamco-cds 없음 (setup.sh 재실행 필요)"
    fi

    # nginx 컨테이너 상태
    CONTAINER_STATUS=$(docker inspect --format '{{.State.Status}}' kamco-train-nginx 2>/dev/null)
    if [ "$CONTAINER_STATUS" = "running" ]; then
        ok "kamco-train-nginx 컨테이너 실행 중"
    elif [ -z "$CONTAINER_STATUS" ]; then
        warn "kamco-train-nginx 컨테이너 없음 (아직 미실행)"
    else
        fail "kamco-train-nginx 컨테이너 상태: $CONTAINER_STATUS"
    fi
else
    fail "Docker 미실행 또는 설치 안 됨"
fi

# ──────────────────────────────────────────
section "nginx 설정 문법 검사"
# ──────────────────────────────────────────
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
    echo "  docker run으로 nginx -t 실행 중..."
    # kamco-cds 네트워크가 있으면 연결 (upstream DNS 조회 가능)
    NETWORK_OPT=""
    if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
        NETWORK_OPT="--network kamco-cds"
    fi
    if docker run --rm $NETWORK_OPT \
        -v "$NGINX_DIR/nginx.conf:/etc/nginx/nginx.conf:ro,Z" \
        -v "$NGINX_DIR/ssl:/etc/nginx/ssl:ro,Z" \
        nginx:alpine nginx -t 2>&1; then
        ok "nginx 설정 문법 OK"
    else
        fail "nginx 설정 문법 오류"
    fi
else
    warn "Docker 없음 - nginx 문법 검사 스킵"
fi

# ──────────────────────────────────────────
section "/etc/hosts 확인"
# ──────────────────────────────────────────
for domain in api.train-kamco.com train-kamco.com; do
    HOSTS_LINE=$(grep "$domain" /etc/hosts | grep -v "^#" | head -1)
    if [ -n "$HOSTS_LINE" ]; then
        ok "$domain 등록됨  →  $HOSTS_LINE"
    else
        fail "$domain /etc/hosts 미등록"
    fi
done

# ──────────────────────────────────────────
section "도메인 해석 확인"
# ──────────────────────────────────────────
for domain in api.train-kamco.com train-kamco.com; do
    RESOLVED=$(getent hosts "$domain" 2>/dev/null | awk '{print $1}' | head -1)
    if [ -n "$RESOLVED" ]; then
        ok "$domain → $RESOLVED"
    else
        fail "$domain 해석 실패 (DNS 또는 hosts 문제)"
    fi
done

# ──────────────────────────────────────────
section "포트 연결 확인 (80 / 443)"
# ──────────────────────────────────────────
for port in 80 443; do
    if command -v nc &>/dev/null; then
        if nc -z -w3 api.train-kamco.com "$port" 2>/dev/null; then
            ok "api.train-kamco.com:$port 열림"
        else
            warn "api.train-kamco.com:$port 닫힘 (nginx 미실행일 수 있음)"
        fi
    elif command -v curl &>/dev/null; then
        HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 3 \
            "$([ "$port" = "443" ] && echo https || echo http)://api.train-kamco.com/" 2>/dev/null)
        if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then
            ok "api.train-kamco.com:$port 응답 (HTTP $HTTP_CODE)"
        else
            warn "api.train-kamco.com:$port 응답 없음 (nginx 미실행일 수 있음)"
        fi
    else
        warn "nc/curl 없음 - 포트 확인 스킵"
        break
    fi
done

# ──────────────────────────────────────────
section "HTTPS 헬스체크"
# ──────────────────────────────────────────
if command -v curl &>/dev/null; then
    for url in \
        "https://api.train-kamco.com/monitor/health" \
        "https://train-kamco.com/monitor/health"; do
        HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url" 2>/dev/null)
        if [ "$HTTP_CODE" = "200" ]; then
            ok "$url → HTTP $HTTP_CODE"
        elif [ "$HTTP_CODE" = "000" ] || [ -z "$HTTP_CODE" ]; then
            warn "$url → 응답 없음 (nginx 미실행일 수 있음)"
        else
            warn "$url → HTTP $HTTP_CODE"
        fi
    done
else
    warn "curl 없음 - HTTPS 헬스체크 스킵"
fi

# ──────────────────────────────────────────
section "결과 요약"
# ──────────────────────────────────────────
echo ""
echo -e "  ${GREEN}PASS: $PASS${NC}  /  ${RED}FAIL: $FAIL${NC}"
echo ""
if [ $FAIL -eq 0 ]; then
    echo -e "${GREEN}모든 체크 통과. nginx 실행 준비 완료.${NC}"
    if [ -n "$DOCKER_COMPOSE" ]; then
        echo "  cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
    else
        echo "  [WARN] docker-compose / docker compose 를 찾을 수 없습니다."
    fi
else
    echo -e "${RED}$FAIL 개 항목 실패. 위 오류를 확인하세요.${NC}"
    exit 1
fi
