#!/bin/bash

# ==============================================================================
# Voitekk Website Deployment Script
# ==============================================================================
# This script automates the deployment of the Voitekk Next.js website on a
# clean Ubuntu server (20.04, 22.04, or 24.04). It handles system updates,
# dependency installation, application setup, and Apache2 reverse proxy config
# for both HTTP (80) and HTTPS (443).
#
# USAGE:
# 1. Upload your project source code to the server.
# 2. Navigate into the project directory.
# 3. Run this script with sudo: `sudo ./deploy.sh`
# ==============================================================================

# --- Script Configuration ---
set -e # Exit immediately if a command exits with a non-zero status.

# --- Helper Functions ---
print_header() {
    echo "=========================================================================="
    echo "$1"
    echo "=========================================================================="
}

print_success() {
    echo "✅ $1"
}

# --- Main Deployment Logic ---

# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root. Please use sudo." >&2
  exit 1
fi

# 1. Welcome and User Input
print_header "Voitekk Website Deployment"
echo "This script will install and configure the Voitekk website from the current directory."
echo "It will set up the site on Port 80 (HTTP) and Port 443 (HTTPS)."
echo "Please provide the following information:"

# Attempt to auto-detect IP
SERVER_IP=$(hostname -I | awk '{print $1}')
read -p "Enter your domain name or server IP address [Default: $SERVER_IP]: " DOMAIN_NAME
DOMAIN_NAME=${DOMAIN_NAME:-$SERVER_IP}

echo ""
echo "-----------------------------------------------------"
echo "Configuration:"
echo "Domain/IP: $DOMAIN_NAME"
echo "Source Directory: $(pwd)"
echo "-----------------------------------------------------"
read -p "Is this correct? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Deployment cancelled."
    exit 1
fi

# 2. System Update
print_header "Step 1: Updating System Packages"
apt update && apt upgrade -y
print_success "System packages updated."

# 3. Install Dependencies
print_header "Step 2: Installing Dependencies (Node.js, Git, Apache2, PM2)"
# Install Git and Apache2
apt install -y curl git apache2 openssl
# Add NodeSource repository for Node.js 20.x
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# Install Node.js
apt install -y nodejs
# Install PM2 process manager globally
npm install -g pm2
print_success "All dependencies installed."

# 4. Configure Apache2
print_header "Step 3: Configuring Apache2 Modules"
a2enmod proxy proxy_http proxy_wstunnel rewrite headers ssl
systemctl restart apache2
print_success "Apache2 modules (including SSL) enabled and service restarted."

# 5. Generate Self-Signed SSL Certificate
print_header "Step 4: Generating Self-Signed SSL Certificate"
# This ensures Apache can start on port 443 immediately
CERT_DIR="/etc/ssl/voitekk"
mkdir -p "$CERT_DIR"
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
    -keyout "$CERT_DIR/voitekk.key" \
    -out "$CERT_DIR/voitekk.crt" \
    -subj "/C=IN/ST=Maharashtra/L=Navi Mumbai/O=Voitekk/OU=IT/CN=$DOMAIN_NAME"
print_success "SSL Certificate generated at $CERT_DIR"

# 6. Copy and Build Application
print_header "Step 5: Copying and Building the Application"
APP_DIR="/var/www/voitekk"
if [ -d "$APP_DIR" ]; then
    read -p "Directory $APP_DIR already exists. Overwrite? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Removing existing directory..."
        rm -rf "$APP_DIR"
    else
        echo "Skipping application setup."
    fi
fi

if [ ! -d "$APP_DIR" ]; then
    echo "Creating application directory at $APP_DIR..."
    mkdir -p "$APP_DIR"
    echo "Copying project files..."
    cp -a . "$APP_DIR/"
    print_success "Project files copied to $APP_DIR."
fi

cd "$APP_DIR"
echo "Installing npm dependencies..."
npm install
print_success "npm dependencies installed."

echo "Creating production build..."
npm run build
print_success "Production build completed."

# 7. Set Ownership and Permissions
print_header "Step 6: Setting File Ownership and Permissions"
chown -R www-data:www-data "$APP_DIR"
print_success "File ownership set to www-data."

# 8. Configure Environment for Email
print_header "Step 7: Configuring Email (Optional)"
echo "To enable the lead capture form, you must configure email server settings."
read -p "Do you want to configure email settings now? (y/n) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    read -p "Enter EMAIL_SERVER_HOST: " EMAIL_SERVER_HOST
    read -p "Enter EMAIL_SERVER_PORT: " EMAIL_SERVER_PORT
    read -p "Enter EMAIL_SERVER_USER: " EMAIL_SERVER_USER
    read -s -p "Enter EMAIL_SERVER_PASSWORD: " EMAIL_SERVER_PASSWORD
    echo ""
    read -p "Enter EMAIL_FROM: " EMAIL_FROM
    read -p "Enter EMAIL_TO: " EMAIL_TO

    bash -c "cat > $APP_DIR/.env.local" <<EOF
# Email Server Configuration
EMAIL_SERVER_HOST=${EMAIL_SERVER_HOST}
EMAIL_SERVER_PORT=${EMAIL_SERVER_PORT}
EMAIL_SERVER_USER=${EMAIL_SERVER_USER}
EMAIL_SERVER_PASSWORD=${EMAIL_SERVER_PASSWORD}
EMAIL_FROM=${EMAIL_FROM}
EMAIL_TO=${EMAIL_TO}
EOF
    chown www-data:www-data "$APP_DIR/.env.local"
    print_success ".env.local file created."
else
    echo "Skipping email configuration."
fi

# 9. Set Up PM2 Process Manager
print_header "Step 8: Setting Up PM2 Process Manager"
cd "$APP_DIR"
PM2_HOME_DIR="$APP_DIR/.pm2"
mkdir -p "$PM2_HOME_DIR"
chown www-data:www-data "$PM2_HOME_DIR"

# Run PM2 commands as www-data with a custom PM2_HOME
sudo -u www-data env PM2_HOME=$PM2_HOME_DIR pm2 delete voitekk || true
sudo -u www-data env PM2_HOME=$PM2_HOME_DIR pm2 start npm --name "voitekk" -- start

# Generate and save startup script
STARTUP_COMMAND=$(pm2 startup systemd -u www-data --hp $PM2_HOME_DIR | grep "sudo")
if [ -n "$STARTUP_COMMAND" ]; then
    eval "$STARTUP_COMMAND"
fi
sudo -u www-data env PM2_HOME=$PM2_HOME_DIR pm2 save

print_success "Application started with PM2."

# 10. Configure Apache Virtual Host
print_header "Step 9: Configuring Apache Virtual Host (Port 80 and 443)"
APACHE_CONF_FILE="/etc/apache2/sites-available/voitekk.conf"
bash -c "cat > ${APACHE_CONF_FILE}" <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN_NAME}
    
    # Redirect all HTTP traffic to HTTPS
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)\$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost *:443>
    ServerName ${DOMAIN_NAME}
    ServerAdmin webmaster@localhost
    
    # SSL Configuration
    SSLEngine on
    SSLCertificateFile $CERT_DIR/voitekk.crt
    SSLCertificateKeyFile $CERT_DIR/voitekk.key

    ProxyPreserveHost On
    ProxyRequests Off
    
    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/

    RewriteEngine On
    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteRule /(.*) ws://localhost:3000/\$1 [P,L]

    ErrorLog \${APACHE_LOG_DIR}/voitekk-error.log
    CustomLog \${APACHE_LOG_DIR}/voitekk-access.log combined
</VirtualHost>
EOF
print_success "Apache Virtual Host file created."

# 11. Enable Site and Finalize
print_header "Step 10: Enabling Site and Finalizing Setup"
a2dissite 000-default.conf || true
a2ensite voitekk.conf
systemctl restart apache2
print_success "Apache restarted and site enabled."

# 12. Completion
print_header "Deployment Complete!"
echo "You can now access your website at: https://${DOMAIN_NAME}"
echo "Note: Since we are using a self-signed certificate, your browser will show a security warning."
echo "      For production, please follow the 'Next Steps' to set up a free SSL with Let's Encrypt."
echo ""
echo "--- Verification ---"
echo "To check Apache: sudo systemctl status apache2"
echo "To check PM2: sudo -u www-data env PM2_HOME=$PM2_HOME_DIR pm2 status"
echo ""
echo "--- Optional Next Steps ---"
echo "To set up a REAL SSL certificate (requires a registered domain):"
echo "  sudo apt install -y certbot python3-certbot-apache"
echo "  sudo certbot --apache -d ${DOMAIN_NAME}"
echo ""
echo "Configure Firewall:"
echo "  sudo ufw allow 'Apache Full'"
echo "  sudo ufw enable"
