#!/bin/bash
# ============================================================================
# SiteBuilder SaaS — Server Setup Script
# ============================================================================
# Run this script ONCE on your server after extracting the sitebuilder package.
#
# Usage:
#   chmod +x setup.sh
#   ./setup.sh
#
# Prerequisites:
#   - Node.js 20 LTS installed (node --version should show v20.x)
#   - npm installed (comes with Node.js)
#
# This script will:
#   1. Install npm dependencies
#   2. Generate encryption keys and JWT secret
#   3. Create the .env file from the template
#   4. Create the SQLite database
#   5. Seed the admin user
#   6. Build the Next.js app for production
#   7. Install PM2 for process management
#   8. Start the app with PM2
#
# After it completes, your app will be running on http://localhost:3000
# Then configure your reverse proxy (Apache/nginx) to forward port 80 → 3000
# ============================================================================

set -e

echo "============================================"
echo "  SiteBuilder SaaS — Server Setup"
echo "============================================"
echo ""

# Check Node.js version
if ! command -v node &> /dev/null; then
    echo "ERROR: Node.js is not installed."
    echo "Please install Node.js 20 LTS first:"
    echo "  curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -"
    echo "  sudo apt-get install -y nodejs"
    exit 1
fi

NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
echo "Node.js version: $(node --version)"
if [ "$NODE_VERSION" -lt 20 ]; then
    echo "WARNING: Node.js version $NODE_VERSION detected. Node.js 20+ is recommended."
    echo "         The app may still work but is tested on v20."
fi

echo ""
echo "npm version: $(npm --version)"
echo ""

# --- Step 1: Install dependencies ---
echo "[1/8] Installing npm dependencies..."
npm install --production=false
echo "  ✓ Dependencies installed"
echo ""

# --- Step 2: Generate keys ---
echo "[2/8] Generating encryption keys and JWT secret..."
ENCRYPTION_KEY=$(openssl rand -hex 32 2>/dev/null || node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
JWT_SECRET=$(openssl rand -hex 32 2>/dev/null || node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
echo "  ✓ Keys generated"
echo ""

# --- Step 3: Create .env file ---
echo "[3/8] Creating .env configuration file..."
if [ -f .env ]; then
    echo "  .env already exists — backing up to .env.backup"
    cp .env .env.backup.$(date +%s)
fi

# Determine the server's public IP or hostname
SERVER_HOST=$(hostname -f 2>/dev/null || hostname 2>/dev/null || echo "localhost")
SERVER_IP=$(curl -s ifconfig.me 2>/dev/null || echo "")

cat > .env << EOF
# ============================================================================
# SiteBuilder SaaS — Production Environment
# ============================================================================

# --- Encryption (auto-generated) ---
ENCRYPTION_KEY=$ENCRYPTION_KEY

# --- App URL ---
# Change this to your actual domain once DNS is configured
APP_BASE_URL=http://${SERVER_IP:-$SERVER_HOST}:3000

# --- File storage ---
EXPORT_DIR=exports

# --- OpenAI API Key (OPTIONAL — leave empty for mock AI) ---
OPENAI_API_KEY=

# --- Auth (auto-generated) ---
JWT_SECRET=$JWT_SECRET

# --- Admin bootstrap credentials ---
ADMIN_EMAIL=admin@instantsitz.com
ADMIN_PASSWORD=ChangeMeNow2025!

# --- Stripe (fill in from your Stripe Dashboard) ---
STRIPE_SECRET_KEY=
STRIPE_PUBLISHABLE_KEY=
STRIPE_WEBHOOK_SECRET=
STRIPE_PRICE_ID=

# --- GoDaddy Domain API (fill in your PAT) ---
GODADDY_PAT=
GODADDY_NAMESERVERS=["ns1.instantsitz.com","ns2.instantsitz.com"]

# --- WHM/cPanel API (fill in from WHM) ---
WHM_API_URL=https://$(hostname -f 2>/dev/null || echo 'your-server'):2087
WHM_API_TOKEN=
WHM_USERNAME=root
WHM_PACKAGE_NAME=default
WHM_IP_ADDRESS=$SERVER_IP

# --- Database ---
DATABASE_URL=file:./dev.db
EOF

echo "  ✓ .env created"
echo "  ⚠ IMPORTANT: Edit .env and fill in your Stripe, GoDaddy, and WHM credentials"
echo ""

# --- Step 4: Create database ---
echo "[4/8] Creating SQLite database..."
npx prisma db push
echo "  ✓ Database created"
echo ""

# --- Step 5: Seed admin user ---
echo "[5/8] Seeding admin user..."
npm run db:seed
echo "  ✓ Admin user created"
echo "  ⚠ Login: admin@instantsitz.com / ChangeMeNow2025!"
echo "  ⚠ Change the password after first login!"
echo ""

# --- Step 6: Build for production ---
echo "[6/8] Building Next.js app for production..."
npm run build
echo "  ✓ Production build complete"
echo ""

# --- Step 7: Install PM2 ---
echo "[7/8] Installing PM2..."
if command -v pm2 &> /dev/null; then
    echo "  PM2 already installed — skipping"
else
    npm install -g pm2
fi
echo "  ✓ PM2 ready"
echo ""

# --- Step 8: Start the app ---
echo "[8/8] Starting the app with PM2..."
pm2 delete sitebuilder 2>/dev/null || true
pm2 start ecosystem.config.js
pm2 save
echo "  ✓ App started"
echo ""

# Try to set up PM2 startup on boot
if [ "$EUID" -eq 0 ] || sudo -n true 2>/dev/null; then
    echo "Configuring PM2 to start on boot..."
    pm2 startup systemd -u $(whoami) --hp $HOME 2>/dev/null || true
    echo "  ✓ PM2 startup configured"
else
    echo "  ℹ Run this to enable PM2 on boot: sudo env PATH=\$PATH:\$(dirname \$(which node)) pm2 startup systemd -u \$(whoami) --hp \$HOME"
fi
echo ""

echo "============================================"
echo "  SETUP COMPLETE!"
echo "============================================"
echo ""
echo "Your SiteBuilder SaaS is now running on port 3000."
echo ""
echo "Admin login: http://$(echo $SERVER_IP || echo 'your-server-ip'):3000/login"
echo "  Email:    admin@instantsitz.com"
echo "  Password: ChangeMeNow2025!"
echo ""
echo "NEXT STEPS:"
echo "  1. Edit .env and fill in your credentials:"
echo "     - Stripe keys (STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY, etc.)"
echo "     - GoDaddy PAT (GODADDY_PAT)"
echo "     - WHM API token (WHM_API_TOKEN)"
echo ""
echo "  2. Restart after editing .env:"
echo "     pm2 restart sitebuilder"
echo ""
echo "  3. Configure a reverse proxy (Apache or nginx) to forward"
echo "     port 80/443 to port 3000 so the app is accessible via"
echo "     your domain name. See DEPLOYMENT.md for details."
echo ""
echo "  4. After first login, change the admin password!"
echo ""
echo "Useful PM2 commands:"
echo "  pm2 status              — check app status"
echo "  pm2 logs sitebuilder    — view logs"
echo "  pm2 restart sitebuilder — restart after .env changes"
echo "  pm2 stop sitebuilder    — stop the app"
echo ""
