#!/usr/bin/env python3
import paramiko, time, sys

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(cmd, timeout=20):
    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: break
        time.sleep(0.2)
    while chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096))
    sys.stdout.flush()
    chan.recv_exit_status()

nginx_conf = r"""server {
    listen 80 default_server;
    server_name _;
    root /var/www/zioinfo;
    index index.html;
    location / {
        try_files $uri $uri/ /index.html;
        add_header Cache-Control no-cache;
    }
    location /api/ {
        proxy_pass         http://127.0.0.1:8082;
        proxy_http_version 1.1;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_read_timeout 60s;
    }
    location ~* \.(js|css|png|jpg|gif|ico|svg|woff2|ttf)$ {
        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/zioinfo', 'w') as f:
    f.write(nginx_conf)
sftp.close()

run('nginx -t && systemctl reload nginx && echo NGINX_OK')
run('curl -s -o /dev/null -w "HTTP %{http_code}" http://localhost/api/company && echo " via Nginx OK"')

client.close()
print('완료')
