#!/bin/bash
# ============================================================
# zio-server 초기 환경 구성 스크립트
# Oracle Cloud Ubuntu 22.04 ARM (Ampere A1)
# 실행: bash 02_server_setup.sh
# ============================================================

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

section "1. 시스템 업데이트"
sudo apt-get update -y && sudo apt-get upgrade -y
sudo apt-get install -y curl wget git unzip net-tools ufw htop
info "시스템 업데이트 완료"

section "2. Java 21 설치 (Spring Boot용)"
sudo apt-get install -y openjdk-21-jdk
java -version
info "Java 21 설치 완료"

section "3. Node.js 20 LTS 설치 (React 빌드용)"
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v && npm -v
info "Node.js $(node -v) 설치 완료"

section "4. Nginx 설치"
sudo apt-get install -y nginx
sudo systemctl enable nginx
sudo systemctl start nginx
info "Nginx 설치 완료"

section "5. UFW 방화벽 설정"
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 8080/tcp
sudo ufw --force enable
sudo ufw status
info "방화벽 설정 완료"

# Oracle Cloud 내부 iptables도 열기 (필수!)
section "6. Oracle Cloud iptables 규칙 추가"
sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 80   -j ACCEPT
sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 443  -j ACCEPT
sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 8080 -j ACCEPT
sudo netfilter-persistent save 2>/dev/null || {
  sudo apt-get install -y iptables-persistent
  sudo netfilter-persistent save
}
info "iptables 규칙 저장 완료"

section "7. 앱 디렉터리 생성"
sudo mkdir -p /var/www/zioinfo
sudo mkdir -p /opt/zioinfo/app
sudo chown -R ubuntu:ubuntu /var/www/zioinfo /opt/zioinfo
info "디렉터리 생성 완료"

section "8. Nginx 설정"
sudo tee /etc/nginx/sites-available/zioinfo > /dev/null <<'NGINX'
server {
    listen 80;
    server_name _;

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

    # React SPA — 모든 경로를 index.html로
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Spring Boot API 프록시
    location /api/ {
        proxy_pass         http://localhost:8080;
        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_read_timeout 60s;
    }

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

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

    # Gzip 압축
    gzip on;
    gzip_types text/plain text/css application/javascript application/json image/svg+xml;
    gzip_min_length 1024;
}
NGINX

sudo ln -sf /etc/nginx/sites-available/zioinfo /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
info "Nginx 설정 완료"

section "✅ 서버 초기 구성 완료!"
echo ""
echo -e "${YELLOW}다음 단계: 로컬에서 03_deploy.sh 실행${NC}"
echo -e "서버 IP: $(curl -s ifconfig.me)"
