#!/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.
# ==============================================================================

# --- 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 ---

# 1. Welcome and User Input
print_header "Voitekk Website Deployment"
echo "This script will install and configure the Voitekk website on this server."
echo "Please provide the following information:"

read -p "Enter your domain name (e.g., voitekk.com): " DOMAIN_NAME
read -p "Enter your Git repository URL: " GIT_REPO_URL

echo ""
echo "-----------------------------------------------------"
echo "Configuration:"
echo "Domain: $DOMAIN_NAME"
echo "Git Repo: $GIT_REPO_URL"
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"
sudo apt update && sudo 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
sudo apt install -y curl git apache2
# Add NodeSource repository for Node.js 20.x
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# Install Node.js
sudo apt install -y nodejs
# Install PM2 process manager globally
sudo npm install -g pm2
print_success "All dependencies installed."

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

# 5. Clone and Build Application
print_header "Step 4: Cloning and Building the Application"
if [ -d "/var/www/voitekk" ]; then
    echo "A directory at /var/www/voitekk already exists. Skipping clone."
else
    sudo git clone "$GIT_REPO_URL" /var/www/voitekk
    print_success "Repository cloned to /var/www/voitekk."
fi

cd /var/www/voitekk
echo "Installing npm dependencies..."
sudo npm install
print_success "npm dependencies installed."

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

# 6. Set Ownership and Permissions
print_header "Step 5: Setting File Ownership and Permissions"
sudo chown -R www-data:www-data /var/www/voitekk
print_success "File ownership set to www-data."

# 7. Configure Environment for Email
print_header "Step 6: 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 (e.g., no-reply@your-domain.com): " EMAIL_FROM
    read -p "Enter EMAIL_TO (e.g., sales@your-domain.com): " EMAIL_TO

    sudo bash -c "cat > /var/www/voitekk/.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
    sudo chown www-data:www-data /var/www/voitekk/.env.local
    print_success ".env.local file created with your email settings."
else
    echo "Skipping email configuration. You can set it up manually later in /var/www/voitekk/.env.local"
fi

# 8. Set Up PM2 Process Manager
print_header "Step 7: Setting Up PM2 Process Manager"
cd /var/www/voitekk
sudo pm2 start npm --name "voitekk" -- start
sudo pm2 startup systemd -u www-data --hp /home/www-data
sudo pm2 save
print_success "Application started with PM2 and configured to start on boot."

# 9. Configure Apache Virtual Host
print_header "Step 8: Configuring Apache Virtual Host"
APACHE_CONF_FILE="/etc/apache2/sites-available/voitekk.conf"
sudo bash -c "cat > ${APACHE_CONF_FILE}" <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN_NAME}
    ServerAdmin webmaster@localhost
    
    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 at ${APACHE_CONF_FILE}."

# 10. Enable Site and Finalize
print_header "Step 9: Enabling Site and Finalizing Setup"
sudo a2dissite 000-default.conf
sudo a2ensite voitekk.conf
sudo systemctl restart apache2
print_success "Default site disabled, voitekk site enabled, and Apache restarted."

# 11. Completion
print_header "Deployment Complete!"
echo "You can now access your website at http://${DOMAIN_NAME}"
echo ""
echo "--- Verification ---"
echo "To check Apache status: sudo systemctl status apache2"
echo "To check application status: sudo pm2 status voitekk"
echo "To view application logs: sudo pm2 logs voitekk"
echo ""
echo "--- Optional Next Steps ---"
echo "Consider securing your site with HTTPS using Let's Encrypt:"
echo "  sudo apt install -y certbot python3-certbot-apache"
echo "  sudo certbot --apache -d ${DOMAIN_NAME}"
echo ""
echo "Consider setting up a firewall:"
echo "  sudo ufw allow 'OpenSSH'"
echo "  sudo ufw allow 'Apache Full'"
echo "  sudo ufw enable"

