#!/usr/bin/env python3
"""Nginx 개방망 설정 배포 스크립트"""
import paramiko, sys, time

HOST = '101.79.17.164'; USER = 'root'; PASS = '1q2w3e!Q'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASS, timeout=15)
sftp = client.open_sftp()

def run(label, cmd, timeout=30):
    print(f'\n[{label}]')
    chan = client.get_transport().open_session()
    chan.set_combine_stderr(True)
    chan.exec_command(cmd)
    start = time.time()
    while not chan.exit_status_ready():
        if chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096)); sys.stdout.flush()
        if time.time() - start > timeout: print('[TIMEOUT]'); break
        time.sleep(0.2)
    while chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096))
    sys.stdout.flush()
    rc = chan.recv_exit_status()
    print(f'exit={rc}'); return rc

# GUARDiA ITSM HTTPS 설정 (포트 443 + 8443)
guardia_https_nginx = r"""# ── GUARDiA ITSM HTTP→HTTPS 리다이렉트 ────────────────────────────────────
server {
    listen 8001;
    server_name _;
    return 301 https://$host:8443$request_uri;
}

# ── GUARDiA ITSM HTTPS ─────────────────────────────────────────────────────
server {
    listen 8443 ssl;
    server_name _;

    ssl_certificate     /etc/ssl/guardia/server.crt;
    ssl_certificate_key /etc/ssl/guardia/server.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 1d;

    client_max_body_size 100M;

    # 보안 헤더
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Rate Limiting (개방망)
    limit_req_zone $binary_remote_addr zone=guardia_api:10m rate=30r/m;

    location / {
        proxy_pass         http://127.0.0.1:8001;
        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 https;
        proxy_read_timeout 300s;
    }

    location /api/ {
        limit_req zone=guardia_api burst=10 nodelay;
        proxy_pass         http://127.0.0.1:8001;
        proxy_http_version 1.1;
        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 https;
        proxy_read_timeout 60s;
    }

    location /api/external/ {
        limit_req zone=guardia_api burst=5 nodelay;
        proxy_pass         http://127.0.0.1:8001;
        proxy_http_version 1.1;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-Proto https;
    }

    location /ws/ {
        proxy_pass         http://127.0.0.1:8001;
        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;
    }
}
"""

# 홈페이지 HTTPS 설정 (포트 443)
zioinfo_https_nginx = r"""# ── 지오정보기술 홈페이지 HTTP→HTTPS ──────────────────────────────────────
server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

# ── 지오정보기술 홈페이지 HTTPS ────────────────────────────────────────────
server {
    listen 443 ssl;
    server_name _;

    ssl_certificate     /etc/ssl/guardia/server.crt;
    ssl_certificate_key /etc/ssl/guardia/server.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

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

    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header X-Content-Type-Options nosniff always;

    location / {
        try_files $uri $uri/ /index.html;
        add_header Cache-Control no-cache;
    }
    location /api/ {
        proxy_pass         http://127.0.0.1:8082;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-Proto https;
        proxy_read_timeout 60s;
    }
    location ~* \.(js|css|png|jpg|gif|ico|svg|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    gzip on;
    gzip_types text/plain text/css application/javascript application/json;
}
"""

with sftp.open('/etc/nginx/sites-available/guardia-https', 'w') as f:
    f.write(guardia_https_nginx)
with sftp.open('/etc/nginx/sites-available/zioinfo-https', 'w') as f:
    f.write(zioinfo_https_nginx)
sftp.close()

# 심볼릭 링크 교체
run('Nginx 사이트 활성화',
    'ln -sf /etc/nginx/sites-available/guardia-https /etc/nginx/sites-enabled/guardia && '
    'ln -sf /etc/nginx/sites-available/zioinfo-https /etc/nginx/sites-enabled/zioinfo && '
    'rm -f /etc/nginx/sites-enabled/guardia-https /etc/nginx/sites-enabled/zioinfo-https && '
    'echo links_ok')

run('UFW 443/8443 포트 오픈',
    'ufw allow 443/tcp && ufw allow 8443/tcp && echo ufw_ok')

run('Nginx 설정 검증',
    'nginx -t')

run('Nginx 리로드',
    'systemctl reload nginx && echo nginx_reloaded')

client.close()
print('\nHTTPS 설정 완료')
