#!/bin/bash
# ============================================================
# Nginx 통합 설정 — zioinfo 홈페이지 + GUARDiA ITSM
# 실행: bash 07_nginx_all.sh [도메인] [itsm도메인]
# 예시: bash 07_nginx_all.sh zioinfo.co.kr itsm.zioinfo.co.kr
# ============================================================

DOMAIN=${1:-"$(curl -s ifconfig.me)"}   # IP 또는 도메인
ITSM_DOMAIN=${2:-"itsm.${DOMAIN}"}

GREEN='\033[0;32m'; CYAN='\033[0;36m'; NC='\033[0m'
info()    { echo -e "${GREEN}[OK]${NC} $1"; }
section() { echo -e "\n${CYAN}=== $1 ===${NC}"; }

section "1. zioinfo 홈페이지 Nginx 설정"
sudo tee /etc/nginx/sites-available/zioinfo <<NGINX
# ──────────────────────────────────────────────
# (주)지오정보기술 홈페이지
# ──────────────────────────────────────────────
server {
    listen 80;
    server_name ${DOMAIN} www.${DOMAIN};

    root /var/www/zioinfo;
    index index.html;

    # React SPA
    location / {
        try_files \$uri \$uri/ /index.html;
        add_header Cache-Control "no-cache";
    }

    # 정적 자산 캐시
    location ~* \.(js|css|png|jpg|gif|ico|svg|woff2|ttf)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Spring Boot API (홈페이지 문의 접수 등)
    location /api/ {
        proxy_pass         http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade \$http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_cache_bypass \$http_upgrade;
    }

    # 보안 헤더
    add_header X-Frame-Options       "SAMEORIGIN"    always;
    add_header X-Content-Type-Options "nosniff"      always;
    add_header Referrer-Policy       "same-origin"   always;

    # gzip
    gzip on;
    gzip_vary on;
    gzip_types text/plain text/css application/javascript application/json image/svg+xml;
    gzip_min_length 1024;
}
NGINX
info "zioinfo 홈페이지 설정 완료"

section "2. GUARDiA ITSM Nginx 설정"
sudo tee /etc/nginx/sites-available/guardia <<NGINX
# ──────────────────────────────────────────────
# GUARDiA ITSM 관리 시스템
# ──────────────────────────────────────────────
upstream guardia_api {
    server 127.0.0.1:8001;
    keepalive 32;
}

server {
    listen 80;
    server_name ${ITSM_DOMAIN};

    client_max_body_size 100M;

    # GUARDiA React SPA + FastAPI
    location / {
        proxy_pass         http://guardia_api;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade \$http_upgrade;
        proxy_set_header   Connection "upgrade";
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
        proxy_read_timeout  300s;
        proxy_send_timeout  300s;
    }

    # WebSocket (SSE + WS)
    location /ws/ {
        proxy_pass         http://guardia_api;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade \$http_upgrade;
        proxy_set_header   Connection "upgrade";
        proxy_set_header   Host \$host;
        proxy_read_timeout 3600s;
    }

    # 정적 파일 직접 서빙 (성능)
    location /static/ {
        alias /opt/guardia/app/static/;
        expires 7d;
    }

    # 업로드 파일
    location /uploads/ {
        alias /opt/guardia/uploads/;
        expires 1d;
    }

    # 보안 — 내부 전용 경로 차단
    location ~ ^/(admin/shell|api/ssh/exec) {
        allow 127.0.0.1;
        deny  all;
        proxy_pass http://guardia_api;
    }

    # 보안 헤더
    add_header X-Frame-Options        "SAMEORIGIN"   always;
    add_header X-Content-Type-Options "nosniff"      always;
    add_header X-XSS-Protection       "1; mode=block" always;

    gzip on;
    gzip_types text/plain text/css application/javascript application/json;
}
NGINX
info "GUARDiA ITSM 설정 완료"

section "3. IP 직접 접속용 기본 설정 (도메인 없을 때)"
sudo tee /etc/nginx/sites-available/default-ip <<NGINX
# IP로 직접 접속 → zioinfo 홈페이지
server {
    listen 80 default_server;
    server_name _;
    root /var/www/zioinfo;
    index index.html;
    location / { try_files \$uri \$uri/ /index.html; }
}

# IP:8001 → GUARDiA ITSM (개발용)
server {
    listen 8001;
    server_name _;
    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
    }
}
NGINX

section "4. 심볼릭 링크 및 설정 적용"
sudo ln -sf /etc/nginx/sites-available/zioinfo   /etc/nginx/sites-enabled/zioinfo
sudo ln -sf /etc/nginx/sites-available/guardia   /etc/nginx/sites-enabled/guardia
sudo ln -sf /etc/nginx/sites-available/default-ip /etc/nginx/sites-enabled/default-ip
sudo rm -f  /etc/nginx/sites-enabled/default

sudo nginx -t
sudo systemctl reload nginx
info "Nginx 설정 적용 완료"

section "5. 상태 확인"
echo ""
echo -e "${GREEN}✅ 서비스 접속 주소${NC}"
echo "  홈페이지:       http://${DOMAIN}"
echo "  GUARDiA ITSM:   http://${ITSM_DOMAIN}"
echo "  (IP 직접)홈:    http://$(curl -s ifconfig.me)"
echo "  (IP 직접)ITSM:  http://$(curl -s ifconfig.me):8001"
