#!/bin/bash

# Next.js Deployment Script for Namecheap VPS
# Run this on your VPS after cloning the repo

# Exit on any error
set -e

echo "🚀 Starting Next.js deployment..."

# Update system
sudo apt update && sudo apt upgrade -y

# Install Node.js (if not already installed)
if ! command -v node &> /dev/null; then
    echo "Installing Node.js..."
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt install -y nodejs
fi

# Install PM2 (process manager)
if ! command -v pm2 &> /dev/null; then
    echo "Installing PM2..."
    sudo npm install -g pm2
fi

# Navigate to project directory
PROJECT_DIR="/home/your-username/your-project-name"
cd $PROJECT_DIR

# Install dependencies
echo "Installing dependencies..."
npm ci

# Build the project
echo "Building Next.js..."
npm run build

# Create PM2 ecosystem config
cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [
    {
      name: 'samer-webshop',
      script: '.next/standalone/server.js',
      instances: 'max',
      exec_mode: 'cluster',
      env: {
        NODE_ENV: 'production',
        PORT: 3000
      },
      error_file: './logs/error.log',
      out_file: './logs/out.log'
    }
  ]
};
EOF

# Create logs directory
mkdir -p logs

# Start the app with PM2
echo "Starting application with PM2..."
pm2 start ecosystem.config.js
pm2 save
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup -u $USER --hp /home/$USER

# Configure Nginx reverse proxy (optional but recommended)
echo "Deployment complete! ✅"
echo "Your app should be running on port 3000"
echo "Next: Configure Nginx as a reverse proxy and point domain to VPS IP"
