#!/bin/bash

# Скрипт для исправления nginx конфигурации с поддержкой SSL
echo "🔧 Исправление nginx конфигурации с SSL поддержкой"
echo "=================================================="

# Создание новой конфигурации nginx с HTTPS
cat > /etc/nginx/sites-available/links << 'EOF'
# HTTP сервер - редирект на HTTPS
server {
    listen 80;
    server_name links.shareon.kr sharon.kr;
    
    # Let's Encrypt challenge
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # Редирект всех HTTP запросов на HTTPS
    location / {
        return 301 https://$server_name$request_uri;
    }
}

# HTTPS сервер
server {
    listen 443 ssl;
    http2 on;
    server_name links.shareon.kr sharon.kr;

    # SSL конфигурация
    ssl_certificate /etc/letsencrypt/live/links.shareon.kr/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/links.shareon.kr/privkey.pem;
    
    # SSL настройки безопасности
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;
    
    # Security headers
    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;

    # Proxy to frontend (Next.js)
    location / {
        proxy_pass http://localhost:3000;
        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_cache_bypass $http_upgrade;
        
        # Timeout настройки
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 86400;
    }

    # Proxy API requests to backend (Django)
    location /api/ {
        proxy_pass http://localhost:8000/api/;
        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;
        
        # CORS headers для API
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
        
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
    }

    # Proxy admin requests to backend (Django)
    location /admin/ {
        proxy_pass http://localhost:8000/admin/;
        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;
    }

    # Serve static files from Django
    location /static/ {
        proxy_pass http://localhost:8000/static/;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto https;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Serve media files from Django
    location /media/ {
        proxy_pass http://localhost:8000/media/;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto https;
        expires 1y;
        add_header Cache-Control "public";
    }
}

# HTTP сервер для localhost (разработка)
server {
    listen 80;
    server_name localhost 127.0.0.1;

    # Proxy to frontend (Next.js)
    location / {
        proxy_pass http://localhost:3000;
        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_cache_bypass $http_upgrade;
        proxy_read_timeout 86400;
    }

    # Proxy API requests to backend (Django)
    location /api/ {
        proxy_pass http://localhost:8000/api/;
        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 admin requests to backend (Django)
    location /admin/ {
        proxy_pass http://localhost:8000/admin/;
        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;
    }

    # Serve static files from Django
    location /static/ {
        proxy_pass http://localhost:8000/static/;
        proxy_set_header Host $host;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Serve media files from Django
    location /media/ {
        proxy_pass http://localhost:8000/media/;
        proxy_set_header Host $host;
        expires 1y;
        add_header Cache-Control "public";
    }
}
EOF

echo "✅ Новая конфигурация nginx создана"

# Проверка синтаксиса
echo "🔍 Проверка синтаксиса nginx..."
if nginx -t; then
    echo "✅ Синтаксис конфигурации корректен"
    
    # Перезапуск nginx
    echo "🔄 Перезапуск nginx..."
    systemctl reload nginx
    
    if systemctl is-active --quiet nginx; then
        echo "✅ nginx успешно перезапущен"
        echo ""
        echo "🎉 Конфигурация nginx обновлена!"
        echo ""
        echo "Теперь доступны:"
        echo "• HTTP -> HTTPS редирект"
        echo "• HTTPS сайт: https://links.shareon.kr"
        echo "• API: https://links.shareon.kr/api/"
        echo "• Admin: https://links.shareon.kr/admin/"
        echo ""
        echo "Проверьте работу:"
        echo "curl -I https://links.shareon.kr/"
        echo "curl -I https://links.shareon.kr/api/"
        echo "curl -I https://links.shareon.kr/admin/"
    else
        echo "❌ Ошибка при перезапуске nginx"
        systemctl status nginx
    fi
else
    echo "❌ Ошибка в синтаксисе конфигурации nginx"
    echo "Восстановление предыдущей конфигурации..."
fi