#!/bin/bash
set -e

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

# 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

echo "=== 디렉토리 생성 ==="
mkdir -p /data/training/request
mkdir -p /data/training/request/tmp
mkdir -p /data/training/response
mkdir -p /data/training/response/v6-cls-checkpoints
mkdir -p /data/training/tmp
mkdir -p "$NGINX_DIR/ssl"
mkdir -p "$NGINX_DIR/logs"
echo "완료"

echo "=== nginx 파일 복사 ==="
cp "$SCRIPT_DIR/nginx.conf" "$NGINX_DIR/"
cp "$SCRIPT_DIR/docker-compose-nginx.yml" "$NGINX_DIR/"
echo "완료"

echo "=== SSL 파일 복사 ==="
cp "$SCRIPT_DIR/ssl/openssl.cnf" "$NGINX_DIR/ssl/"
cp "$SCRIPT_DIR/ssl/train-kamco.com.crt" "$NGINX_DIR/ssl/"
cp "$SCRIPT_DIR/ssl/train-kamco.com.key" "$NGINX_DIR/ssl/"
echo "완료"

echo "=== SSL 권한 설정 ==="
chmod 700 "$NGINX_DIR/ssl"
chmod 600 "$NGINX_DIR/ssl/train-kamco.com.key"
chmod 644 "$NGINX_DIR/ssl/train-kamco.com.crt"
echo "완료"

echo "=== 소유권 설정 (kcomu:kcomu) ==="
chown -R kcomu:kcomu /data/training
echo "완료"

echo "=== 그룹 설정 (setup-groups.sh) ==="
bash "$SCRIPT_DIR/setup-groups.sh"

echo "=== docker-compose-nginx.yml 소유권 설정 (1000:1000) ==="
chown 1000:1000 "$NGINX_DIR/docker-compose-nginx.yml"
echo "완료"

echo "=== docker-compose 래퍼 설정 ==="
if command -v docker-compose &>/dev/null; then
    echo "docker-compose 이미 설치됨 (스킵)"
elif docker compose version &>/dev/null 2>&1; then
    cat > /usr/local/bin/docker-compose << 'EOF'
#!/bin/bash
exec docker compose "$@"
EOF
    chmod +x /usr/local/bin/docker-compose
    echo "docker-compose → docker compose 래퍼 생성 완료"
    DOCKER_COMPOSE="docker-compose"
else
    echo "[WARN] docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
fi

echo "=== Docker network 설정 ==="
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
    echo "kamco-cds 네트워크 이미 존재 (스킵)"
else
    docker network create kamco-cds
    echo "kamco-cds 네트워크 생성 완료"
fi

echo "=== /etc/hosts 설정 ==="
if grep -q "train-kamco.com" /etc/hosts; then
    echo "이미 설정되어 있음 (스킵)"
else
    echo "127.0.0.1   api.train-kamco.com train-kamco.com" >> /etc/hosts
    echo "추가 완료"
fi
echo "현재 hosts 설정:"
grep "train-kamco" /etc/hosts

echo ""
echo "=== 설치 완료 ==="
echo "생성된 디렉토리:"
find /data -type d | sort
echo ""
echo "=== nginx 실행 방법 ==="
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 를 찾을 수 없습니다. Docker 설치를 확인하세요."
fi
