#!/bin/bash

# update_remote_nginx_conf.sh
# Updates the remote nginx configuration on laantungir.net
# Copies contents of ./remote.nginx.config to /etc/nginx/conf.d/default.conf

set -e

echo "=== Updating Remote Nginx Configuration ==="
echo "Server: laantungir.net"
echo "User: ubuntu"
echo "Local config: ./remote.nginx.config"
echo "Remote config: /etc/nginx/conf.d/default.conf"
echo

# Check if local config exists
if [[ ! -f "./remote.nginx.config" ]]; then
    echo "ERROR: ./remote.nginx.config not found"
    exit 1
fi

echo "Copying remote.nginx.config to laantungir.net:/etc/nginx/conf.d/default.conf..."

# Copy the config file to the remote server (using user's home directory)
scp ./remote.nginx.config ubuntu@laantungir.net:~/remote.nginx.config

# Move to final location and backup old config
ssh ubuntu@laantungir.net << 'EOF'
    echo "Creating backup of current config..."
    sudo cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.backup.$(date +%Y%m%d_%H%M%S)

    echo "Installing new config..."
    sudo cp ~/remote.nginx.config /etc/nginx/conf.d/default.conf

    echo "Testing nginx configuration..."
    if sudo nginx -t; then
        echo "✅ Nginx config test passed"
        echo "Reloading nginx..."
        sudo nginx -s reload
        echo "✅ Nginx reloaded successfully"
    else
        echo "❌ Nginx config test failed"
        echo "Restoring backup..."
        sudo cp /etc/nginx/conf.d/default.conf.backup.* /etc/nginx/conf.d/default.conf 2>/dev/null || true
        exit 1
    fi

    echo "Cleaning up temporary file..."
    rm ~/remote.nginx.config
EOF

echo
echo "=== Update Complete ==="
echo "The remote nginx configuration has been updated."
