#!/bin/bash
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   print_error "This script must be run as root (use sudo)"
   exit 1
fi

# Check if argument is provided
if [ $# -eq 0 ]; then
    print_error "Usage: sudo ./deploy.sh [simple|production]"
    echo ""
    echo "Available modes:"
    echo "  simple     - Deploy for direct IP access (e.g., http://203.0.113.55:8080)"
    echo "  production - Deploy with Nginx reverse proxy for domain access"
    exit 1
fi

MODE=$1
APP_DIR="/opt/optimization-factory"
SERVICE_NAME="optimization-factory"

print_status "Starting deployment in '$MODE' mode..."

# Common setup for both modes
print_status "Performing common setup..."

# Update package list
apt-get update -y

# Install common dependencies
print_status "Installing common dependencies..."
apt-get install -y git python3-pip python3-venv curl awscli

# Copy or update the application from current directory
print_status "Copying application from current project directory..."
# Get the current script directory and go up one level to get the project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Pre-copy: remove repo symlinks that could cause circular references on copy
print_status "Cleaning repository symlinks (pre-copy)..."
if [ -L "$PROJECT_ROOT/server/jobs.json" ]; then
    rm -f "$PROJECT_ROOT/server/jobs.json"
    print_status "Removed repo symlink: server/jobs.json"
fi
if [ -L "$PROJECT_ROOT/config" ]; then
    rm -f "$PROJECT_ROOT/config"
    print_status "Removed repo symlink: config"
fi
if [ -L "$PROJECT_ROOT/.env" ]; then
    rm -f "$PROJECT_ROOT/.env"
    print_status "Removed repo symlink: .env"
fi

# --- START: NEW DATA PRESERVATION AND FILE COPY LOGIC ---

# First, check if the source .env file exists. This is a critical pre-deployment check.
if [ ! -f "$PROJECT_ROOT/.env" ]; then
    print_error ".env file not found in your project directory ($PROJECT_ROOT/.env)"
    print_error "Please create it by copying 'env.example' and configuring your settings."
    exit 1
fi

PRESERVE_DIR="" # Initialize preservation directory variable

# If the application is already deployed, preserve its live data.
if [ -d "$APP_DIR" ]; then
    print_status "Existing deployment found. Preserving live data..."
    PRESERVE_DIR="/tmp/optimization-factory-preserve-$(date +%s)"
    mkdir -p "$PRESERVE_DIR"

    # Move the 'config' directory (which contains 'analysis' folder) if it's a real directory
    if [ -d "$APP_DIR/config" ] && [ ! -L "$APP_DIR/config" ]; then
        mv "$APP_DIR/config" "$PRESERVE_DIR/config"
        print_status "Preserved 'config' directory."
    fi
    
    # Move the 'jobs.json' file if it's a real file
    if [ -f "$APP_DIR/server/jobs.json" ] && [ ! -L "$APP_DIR/server/jobs.json" ]; then
        mkdir -p "$PRESERVE_DIR/server"
        mv "$APP_DIR/server/jobs.json" "$PRESERVE_DIR/server/jobs.json"
        print_status "Preserved 'jobs.json' data file."
    fi
    
    # Remove the old application directory for a clean copy
    print_status "Removing old application code..."
    rm -rf "$APP_DIR"
fi

# Copy the entire project to the target directory. The `/.` ensures hidden files like .env are included.
print_status "Copying new application files to $APP_DIR..."
mkdir -p "$APP_DIR"
cp -r "$PROJECT_ROOT"/. "$APP_DIR"/ || { print_error "Failed to copy application files"; exit 1; }
cd "$APP_DIR"

# Restore the preserved live data, overwriting the template versions from the source repo
if [ -n "$PRESERVE_DIR" ]; then
    print_status "Restoring live data..."

    if [ -d "$PRESERVE_DIR/config" ]; then
        rm -rf "$APP_DIR/config" # Remove the template config dir just copied
        mv "$PRESERVE_DIR/config" "$APP_DIR/config"
        print_success "Restored 'config' directory."
    fi

    if [ -f "$PRESERVE_DIR/server/jobs.json" ]; then
        # Ensure the server directory exists before moving the file back
        mkdir -p "$APP_DIR/server"
        mv "$PRESERVE_DIR/server/jobs.json" "$APP_DIR/server/jobs.json"
        print_success "Restored 'jobs.json' file."
    fi

    # Clean up the temporary preservation directory
    rm -rf "$PRESERVE_DIR"
    print_status "Cleaned up temporary backup files."
fi

# --- END: NEW DATA PRESERVATION AND FILE COPY LOGIC ---

# Set proper ownership and permissions for www-data user
print_status "Setting proper permissions..."
chown -R www-data:www-data "$APP_DIR"
chmod -R 755 "$APP_DIR"

# Ensure www-data can write to necessary directories
mkdir -p "$APP_DIR/server/logs"
mkdir -p "$APP_DIR/config/analysis"
chown -R www-data:www-data "$APP_DIR/server/logs" "$APP_DIR/config"
chmod -R 775 "$APP_DIR/server/logs" "$APP_DIR/config"


# Create virtual environment
print_status "Setting up Python virtual environment..."
if [ ! -d "$APP_DIR/venv" ]; then
    python3 -m venv "$APP_DIR/venv"
fi

# Activate virtual environment and install dependencies
print_status "Installing Python dependencies..."
source "$APP_DIR/venv/bin/activate"
pip install --upgrade pip
pip install -r "$APP_DIR/tools/requirements.txt"
pip install gunicorn

            # Check if .env file exists
            if [ ! -f "$APP_DIR/.env" ]; then
                print_warning ".env file not found at $APP_DIR/.env"
                print_warning "Please create it by copying env.example and configuring your settings"
                print_warning "For simple mode, ensure PORT is set (e.g., PORT=8080)"
                exit 1
            fi
            
            # Verify AWS configuration
            print_status "Verifying AWS configuration..."
            
            # Check if AWS credentials are in .env file
            AWS_ACCESS_KEY_ID=$(grep "^AWS_ACCESS_KEY_ID=" "$APP_DIR/.env" | cut -d'=' -f2 | tr -d '"' | tr -d "'")
            AWS_SECRET_ACCESS_KEY=$(grep "^AWS_SECRET_ACCESS_KEY=" "$APP_DIR/.env" | cut -d'=' -f2 | tr -d '"' | tr -d "'")
            
            if [ ! -z "$AWS_ACCESS_KEY_ID" ] && [ ! -z "$AWS_SECRET_ACCESS_KEY" ]; then
                print_success "AWS credentials found in .env file"
                
                # Test AWS credentials by setting environment variables
                export AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID"
                export AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY"
                export AWS_DEFAULT_REGION=$(grep "^AWS_DEFAULT_REGION=" "$APP_DIR/.env" | cut -d'=' -f2 | tr -d '"' | tr -d "'" || echo "us-east-1")
                
                if aws sts get-caller-identity >/dev/null 2>&1; then
                    print_success "AWS credentials verified successfully"
                else
                    print_warning "AWS credentials in .env file are invalid"
                    print_warning "Please check your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY values"
                fi
            elif aws sts get-caller-identity >/dev/null 2>&1; then
                print_success "AWS credentials verified successfully (system-wide configuration)"
            else
                print_warning "AWS credentials not configured or invalid"
                print_warning "Please configure AWS credentials using one of these methods:"
                print_warning "1. Attach an IAM role to your EC2 instance (recommended)"
                print_warning "2. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in your .env file"
                print_warning "Continuing deployment, but the application may not function properly without AWS access..."
            fi
            
            # SSH Key Setup for www-data user
            print_status "Setting up SSH keys for www-data user..."
            
            # Extract SSH key name from existing SSH_KEY_PATH in .env file
            SSH_KEY_NAME=""
            if grep -q "^SSH_KEY_PATH=" "$APP_DIR/.env"; then
                SSH_KEY_PATH=$(grep "^SSH_KEY_PATH=" "$APP_DIR/.env" | cut -d'=' -f2 | tr -d '"' | tr -d "'")
                SSH_KEY_NAME=$(basename "$SSH_KEY_PATH")
                print_status "Found SSH key name in .env: $SSH_KEY_NAME"
            else
                print_warning "SSH_KEY_PATH not found in .env file, using default key name"
                SSH_KEY_NAME="Deployed_Optimization_Factory_key_pair.pem"
            fi
            
            # Create .ssh directory for www-data user
            mkdir -p /var/www/.ssh
            chown -R www-data:www-data /var/www/.ssh
            chmod 700 /var/www/.ssh
            
            SSH_KEY_COPIED=false
            
            # Check if SSH key exists in ubuntu user's directory
            if [ -f "/home/ubuntu/.ssh/$SSH_KEY_NAME" ]; then
                print_status "Found SSH key '$SSH_KEY_NAME' in ubuntu user directory, copying to www-data..."
                cp "/home/ubuntu/.ssh/$SSH_KEY_NAME" "/var/www/.ssh/$SSH_KEY_NAME"
                chown www-data:www-data "/var/www/.ssh/$SSH_KEY_NAME"
                chmod 600 "/var/www/.ssh/$SSH_KEY_NAME"
                SSH_KEY_COPIED=true
                print_success "SSH key copied successfully"
                
                # Convert RSA key to OpenSSH format if needed
                print_status "Checking SSH key format compatibility..."
                if head -1 "/var/www/.ssh/$SSH_KEY_NAME" | grep -q "BEGIN RSA PRIVATE KEY"; then
                    print_status "Converting RSA key to OpenSSH format for Paramiko compatibility..."
                    
                    # Create a backup of the original key
                    cp "/var/www/.ssh/$SSH_KEY_NAME" "/var/www/.ssh/${SSH_KEY_NAME}.backup"
                    
                    # Method 1: Try ssh-keygen conversion
                    if ssh-keygen -p -m OpenSSH -f "/var/www/.ssh/$SSH_KEY_NAME" -N "" 2>/dev/null; then
                        print_success "SSH key converted to OpenSSH format successfully (method 1)"
                    else
                        print_warning "Method 1 failed, trying alternative conversion..."
                        
                        # Method 2: Try ssh-keygen with different parameters
                        if ssh-keygen -p -m OpenSSH -f "/var/www/.ssh/${SSH_KEY_NAME}.backup" -N "" 2>/dev/null; then
                            mv "/var/www/.ssh/${SSH_KEY_NAME}.backup" "/var/www/.ssh/$SSH_KEY_NAME"
                            print_success "SSH key converted to OpenSSH format successfully (method 2)"
                        else
                            print_warning "Method 2 failed, trying manual conversion..."
                            
                            # Method 3: Generate new OpenSSH key (safer than manual conversion)
                            if ssh-keygen -t rsa -b 4096 -f "/var/www/.ssh/$SSH_KEY_NAME" -N '' -m OpenSSH 2>/dev/null; then
                                print_success "SSH key converted to OpenSSH format successfully (method 3 - new key generated)"
                                print_warning "Note: A new SSH key was generated. You may need to add the public key to your EC2 instances."
                                print_status "Public key: $(ssh-keygen -y -f "/var/www/.ssh/$SSH_KEY_NAME" 2>/dev/null || echo 'Unable to extract public key')"
                            else
                                print_warning "All conversion methods failed, but continuing with original key"
                            fi
                        fi
                    fi
                    
                    # Clean up backup
                    rm -f "/var/www/.ssh/${SSH_KEY_NAME}.backup"
                    
                    # Ensure correct ownership after conversion
                    chown www-data:www-data "/var/www/.ssh/$SSH_KEY_NAME"
                    chmod 600 "/var/www/.ssh/$SSH_KEY_NAME"
                    
                elif head -1 "/var/www/.ssh/$SSH_KEY_NAME" | grep -q "BEGIN.*PRIVATE KEY"; then
                    print_success "SSH key format is already compatible"
                else
                    print_warning "SSH key format may be invalid - check the key file"
                fi
                
                # Verify the key format and permissions
                print_status "Verifying SSH key setup..."
                if [ -f "/var/www/.ssh/$SSH_KEY_NAME" ]; then
                    KEY_PERMS=$(stat -c "%a" "/var/www/.ssh/$SSH_KEY_NAME")
                    KEY_OWNER=$(stat -c "%U:%G" "/var/www/.ssh/$SSH_KEY_NAME")
                    print_status "SSH key permissions: $KEY_PERMS, owner: $KEY_OWNER"
                    
                    # Test SSH key with ssh-keygen
                    if ssh-keygen -y -f "/var/www/.ssh/$SSH_KEY_NAME" >/dev/null 2>&1; then
                        print_success "SSH key validation passed"
                    else
                        print_warning "SSH key validation failed - may cause connection issues"
                    fi
                fi
            elif [ -f "/root/.ssh/$SSH_KEY_NAME" ]; then
                print_status "Found SSH key '$SSH_KEY_NAME' in root directory, copying to www-data..."
                cp "/root/.ssh/$SSH_KEY_NAME" "/var/www/.ssh/$SSH_KEY_NAME"
                chown www-data:www-data "/var/www/.ssh/$SSH_KEY_NAME"
                chmod 600 "/var/www/.ssh/$SSH_KEY_NAME"
                SSH_KEY_COPIED=true
                print_success "SSH key copied successfully"
                
                # Convert RSA key to OpenSSH format if needed
                print_status "Checking SSH key format compatibility..."
                if head -1 "/var/www/.ssh/$SSH_KEY_NAME" | grep -q "BEGIN RSA PRIVATE KEY"; then
                    print_status "Converting RSA key to OpenSSH format for Paramiko compatibility..."
                    
                    # Create a backup of the original key
                    cp "/var/www/.ssh/$SSH_KEY_NAME" "/var/www/.ssh/${SSH_KEY_NAME}.backup"
                    
                    # Method 1: Try ssh-keygen conversion
                    if ssh-keygen -p -m OpenSSH -f "/var/www/.ssh/$SSH_KEY_NAME" -N "" 2>/dev/null; then
                        print_success "SSH key converted to OpenSSH format successfully (method 1)"
                    else
                        print_warning "Method 1 failed, trying alternative conversion..."
                        
                        # Method 2: Try ssh-keygen with different parameters
                        if ssh-keygen -p -m OpenSSH -f "/var/www/.ssh/${SSH_KEY_NAME}.backup" -N "" 2>/dev/null; then
                            mv "/var/www/.ssh/${SSH_KEY_NAME}.backup" "/var/www/.ssh/$SSH_KEY_NAME"
                            print_success "SSH key converted to OpenSSH format successfully (method 2)"
                        else
                            print_warning "Method 2 failed, trying manual conversion..."
                            
                            # Method 3: Generate new OpenSSH key (safer than manual conversion)
                            if ssh-keygen -t rsa -b 4096 -f "/var/www/.ssh/$SSH_KEY_NAME" -N '' -m OpenSSH 2>/dev/null; then
                                print_success "SSH key converted to OpenSSH format successfully (method 3 - new key generated)"
                                print_warning "Note: A new SSH key was generated. You may need to add the public key to your EC2 instances."
                                print_status "Public key: $(ssh-keygen -y -f "/var/www/.ssh/$SSH_KEY_NAME" 2>/dev/null || echo 'Unable to extract public key')"
                            else
                                print_warning "All conversion methods failed, but continuing with original key"
                            fi
                        fi
                    fi
                    
                    # Clean up backup
                    rm -f "/var/www/.ssh/${SSH_KEY_NAME}.backup"
                    
                    # Ensure correct ownership after conversion
                    chown www-data:www-data "/var/www/.ssh/$SSH_KEY_NAME"
                    chmod 600 "/var/www/.ssh/$SSH_KEY_NAME"
                    
                elif head -1 "/var/www/.ssh/$SSH_KEY_NAME" | grep -q "BEGIN.*PRIVATE KEY"; then
                    print_success "SSH key format is already compatible"
                else
                    print_warning "SSH key format may be invalid - check the key file"
                fi
                
                # Verify the key format and permissions
                print_status "Verifying SSH key setup..."
                if [ -f "/var/www/.ssh/$SSH_KEY_NAME" ]; then
                    KEY_PERMS=$(stat -c "%a" "/var/www/.ssh/$SSH_KEY_NAME")
                    KEY_OWNER=$(stat -c "%U:%G" "/var/www/.ssh/$SSH_KEY_NAME")
                    print_status "SSH key permissions: $KEY_PERMS, owner: $KEY_OWNER"
                    
                    # Test SSH key with ssh-keygen
                    if ssh-keygen -y -f "/var/www/.ssh/$SSH_KEY_NAME" >/dev/null 2>&1; then
                        print_success "SSH key validation passed"
                    else
                        print_warning "SSH key validation failed - may cause connection issues"
                    fi
                fi
            else
                print_warning "SSH key '$SSH_KEY_NAME' not found in common locations:"
                print_warning "- /home/ubuntu/.ssh/"
                print_warning "- /root/.ssh/"
                print_warning "Please ensure your SSH key is available for the application to connect to optimization instances"
                print_warning "You can copy it manually:"
                print_warning "  sudo cp /path/to/your/$SSH_KEY_NAME /var/www/.ssh/$SSH_KEY_NAME"
                print_warning "  sudo chown www-data:www-data /var/www/.ssh/$SSH_KEY_NAME"
                print_warning "  sudo chmod 600 /var/www/.ssh/$SSH_KEY_NAME"
                print_warning "  # If you get 'encountered RSA key, expected OPENSSH key' error, convert the key:"
                print_warning "  sudo ssh-keygen -p -m OpenSSH -f /var/www/.ssh/$SSH_KEY_NAME -N ''"
            fi
            
            # Update .env file to use absolute SSH key path for www-data user
            if [ "$SSH_KEY_COPIED" = true ]; then
                print_status "Updating .env file with correct SSH key path..."
                
                # Update SSH_KEY_PATH to use absolute path for www-data user
                NEW_SSH_KEY_PATH="/var/www/.ssh/$SSH_KEY_NAME"
                if grep -q "^SSH_KEY_PATH=" "$APP_DIR/.env"; then
                    # Update existing SSH_KEY_PATH
                    sed -i "s|^SSH_KEY_PATH=.*|SSH_KEY_PATH=$NEW_SSH_KEY_PATH|" "$APP_DIR/.env"
                else
                    # Add SSH_KEY_PATH if it doesn't exist
                    echo "SSH_KEY_PATH=$NEW_SSH_KEY_PATH" >> "$APP_DIR/.env"
                fi
                
                print_success "SSH key path updated in .env file: $NEW_SSH_KEY_PATH"
            fi

# Mode-specific configuration
case $MODE in
    "simple")
        print_status "Configuring for Simple IP-Based Deployment..."
        
        # Cleanup any existing production configuration
        print_status "Cleaning up any existing production configuration..."
        systemctl stop nginx 2>/dev/null || true
        systemctl disable nginx 2>/dev/null || true
        rm -f /etc/nginx/sites-enabled/optimization-factory 2>/dev/null || true
        rm -f /etc/nginx/sites-available/optimization-factory 2>/dev/null || true
        ufw delete allow 'Nginx Full' 2>/dev/null || true
        
        # Read PORT from .env file
        PORT=$(grep "^PORT=" "$APP_DIR/.env" | cut -d'=' -f2 | tr -d '"' | tr -d "'")
        if [ -z "$PORT" ]; then
            print_error "PORT not found in .env file. Please set PORT=8080 (or your preferred port) in $APP_DIR/.env"
            exit 1
        fi
        
        print_status "Using port: $PORT"
        
        # Configure firewall
        print_status "Configuring firewall..."
        ufw --force enable
        ufw allow OpenSSH
        ufw allow "$PORT/tcp"
        
        # Create systemd service file
        print_status "Creating systemd service..."
        cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=Optimization Factory Web Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=$APP_DIR
EnvironmentFile=$APP_DIR/.env
ExecStart=$APP_DIR/venv/bin/gunicorn --workers 3 --timeout 300 --bind 0.0.0.0:$PORT server.app:app
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF
        
        # Reload systemd and start service
        print_status "Starting service..."
        systemctl daemon-reload
        systemctl enable $SERVICE_NAME
        systemctl restart $SERVICE_NAME
        
        # Get server IP
        SERVER_IP=$(curl -s ifconfig.me || curl -s ipinfo.io/ip || echo "YOUR_SERVER_IP")
        
        print_success "Simple deployment completed!"
        print_success "Your application is now accessible at: http://$SERVER_IP:$PORT"
        print_status "Service status: $(systemctl is-active $SERVICE_NAME)"
        ;;
        
    "production")
        print_status "Configuring for Production Deployment with Nginx..."
        
        # Cleanup any existing simple configuration
        print_status "Cleaning up any existing simple configuration..."
        if [ -f "$APP_DIR/.env" ]; then
            SIMPLE_PORT=$(grep "^PORT=" "$APP_DIR/.env" | cut -d'=' -f2 | tr -d '"' | tr -d "'")
            if [ ! -z "$SIMPLE_PORT" ]; then
                ufw delete allow "$SIMPLE_PORT/tcp" 2>/dev/null || true
            fi
        fi
        
        # Install Nginx
        print_status "Installing Nginx..."
        apt-get install -y nginx
        
        # Configure firewall
        print_status "Configuring firewall..."
        ufw --force enable
        ufw allow OpenSSH
        ufw allow 'Nginx Full'
        
        # Create systemd service file
        print_status "Creating systemd service..."
        cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=Optimization Factory Web Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=$APP_DIR
EnvironmentFile=$APP_DIR/.env
ExecStart=$APP_DIR/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock -m 007 server.app:app
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF
        
        # Create Nginx configuration
        print_status "Configuring Nginx..."
        cat > /etc/nginx/sites-available/optimization-factory << EOF
server {
    listen 80;
    server_name your_domain.com; # <-- CHANGE THIS TO YOUR ACTUAL DOMAIN
    
    location / {
        proxy_pass http://unix:/run/gunicorn.sock;
        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_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
}
EOF
        
        # Enable the site
        ln -sf /etc/nginx/sites-available/optimization-factory /etc/nginx/sites-enabled/
        rm -f /etc/nginx/sites-enabled/default
        
        # Test Nginx configuration
        print_status "Testing Nginx configuration..."
        nginx -t
        
        # Reload systemd and start services
        print_status "Starting services..."
        systemctl daemon-reload
        systemctl enable $SERVICE_NAME
        systemctl enable nginx
        systemctl restart $SERVICE_NAME
        systemctl restart nginx
        
        print_success "Production deployment completed!"
        print_success "Next steps:"
        print_status "1. Update your domain DNS to point to this server's IP"
        print_status "2. Edit /etc/nginx/sites-available/optimization-factory and replace 'your_domain.com' with your actual domain"
        print_status "3. Restart Nginx: sudo systemctl restart nginx"
        print_status "4. Install Certbot and enable SSL:"
        print_status "   sudo apt install certbot python3-certbot-nginx"
        print_status "   sudo certbot --nginx -d your_domain.com"
        print_status "Service status: $(systemctl is-active $SERVICE_NAME)"
        print_status "Nginx status: $(systemctl is-active nginx)"
        ;;
        
    *)
        print_error "Invalid mode: $MODE"
        print_error "Usage: sudo ./deploy.sh [simple|production]"
        exit 1
        ;;
esac

print_success "Deployment completed successfully!"
print_status "To view logs: sudo journalctl -u $SERVICE_NAME -f"
if [ "$MODE" = "production" ]; then
    print_status "To view Nginx logs: sudo tail -f /var/log/nginx/access.log"
fi
