#!/usr/bin/env bash
# ============================================================
# BulkMailer Pro — cPanel / Shared Hosting Build Script
# ============================================================
# Run this from the project root:
#   bash scripts/build-cpanel.sh
#
# Output: a self-contained folder at ./cpanel-dist/ that you
# upload to your cPanel server.
# ============================================================

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/cpanel-dist"

echo ""
echo "╔══════════════════════════════════════════════╗"
echo "║       BulkMailer Pro — cPanel Build          ║"
echo "╚══════════════════════════════════════════════╝"
echo ""

# ── Step 1: Clean output ────────────────────────────────────
echo "→ Cleaning previous build..."
rm -rf "$OUT"
mkdir -p "$OUT/public"

# ── Step 2: Build React frontend ───────────────────────────
echo "→ Building frontend..."
cd "$ROOT"
PORT=3000 BASE_PATH=/ pnpm --filter @workspace/bulkmailer-pro run build

echo "→ Copying frontend files..."
cp -r "$ROOT/artifacts/bulkmailer-pro/dist/public/." "$OUT/public/"

# ── Step 3: Build API server ────────────────────────────────
echo "→ Building API server..."
pnpm --filter @workspace/api-server run build

echo "→ Copying API server files..."
cp -r "$ROOT/artifacts/api-server/dist/." "$OUT/dist/"

# ── Step 4: Create standalone package.json ─────────────────
echo "→ Writing production package.json..."
cat > "$OUT/package.json" <<'PKGJSON'
{
  "name": "bulkmailer-pro-server",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node --enable-source-maps dist/index.mjs"
  },
  "dependencies": {
    "bcryptjs": "^3.0.2",
    "cookie-parser": "^1.4.7",
    "cors": "^2.8.5",
    "drizzle-orm": "^0.44.2",
    "express": "^5.1.0",
    "pg": "^8.16.0",
    "pino": "^9.7.0",
    "pino-http": "^10.4.0",
    "pino-pretty": "^13.0.0"
  }
}
PKGJSON

# ── Step 5: Create .env.example ────────────────────────────
echo "→ Writing .env.example..."
cat > "$OUT/.env.example" <<'ENVEX'
# ── Required ──────────────────────────────────────────────
# Your PostgreSQL database connection string
DATABASE_URL=postgresql://user:password@localhost:5432/bulkmailer

# Secret key for encrypting stored API keys (any random 32+ char string)
SESSION_SECRET=change-me-to-a-long-random-secret-string

# ── Optional but recommended ──────────────────────────────
# Port the Node.js server listens on (cPanel Node.js Selector sets this automatically)
PORT=3000

# Set to "true" so the server also serves the React frontend from ./public/
SERVE_STATIC=true

# Path to the built React app (relative to server working dir, default: "public")
STATIC_DIR=public

# Admin panel password (default: ValidAdmin2026!)
ADMIN_PASSWORD=your-secure-admin-password

# Your site's public URL — used in password reset emails
SITE_URL=https://yourdomain.com

# Node environment
NODE_ENV=production
ENVEX

# ── Step 6: Create .htaccess for static-only hosting ───────
echo "→ Writing .htaccess for Apache (static fallback)..."
cat > "$OUT/public/.htaccess" <<'HTACCESS'
# BulkMailer Pro — Apache SPA Routing
# If you host ONLY the frontend on cPanel (with API on a separate server),
# this ensures React Router works for all pages.

Options -MultiViews
RewriteEngine On

# If the request is for an existing file or directory, serve it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite everything else to index.html
RewriteRule ^ index.html [QSA,L]
HTACCESS

# ── Step 7: Write setup README ──────────────────────────────
echo "→ Writing CPANEL-SETUP.md..."
cat > "$OUT/CPANEL-SETUP.md" <<'README'
# BulkMailer Pro — cPanel Deployment Guide

This folder contains everything you need to run BulkMailer Pro on cPanel.

---

## Option A — Single Node.js App (Recommended)

Use this if your cPanel host supports **Node.js Selector** (most modern cPanel hosts do).

### 1. Create a PostgreSQL database
In cPanel → PostgreSQL Databases, create a database and user. Note the connection details.

### 2. Upload files
Upload the **entire contents** of this `cpanel-dist/` folder to your Node.js app directory
(usually something like `/home/youruser/nodevenv/myapp/`).

### 3. Set environment variables
In cPanel → Node.js Selector → your app → Environment Variables, add:

| Variable | Value |
|---|---|
| `DATABASE_URL` | `postgresql://user:pass@localhost:5432/dbname` |
| `SESSION_SECRET` | Any long random string (32+ chars) |
| `SERVE_STATIC` | `true` |
| `STATIC_DIR` | `public` |
| `SITE_URL` | `https://yourdomain.com` |
| `NODE_ENV` | `production` |
| `ADMIN_PASSWORD` | Your secure admin password |

### 4. Set startup file
In Node.js Selector, set the **Application startup file** to: `dist/index.mjs`

### 5. Install dependencies and start
```bash
npm install --omit=dev
npm start
```

### 6. Run database migrations (first time only)
The database schema is automatically applied on first request — no manual migration needed.

---

## Option B — Frontend Only (Static Files)

If you only want to host the **frontend** on cPanel and run the API server separately:

1. Upload the contents of `public/` to your `public_html/` folder.
2. The `.htaccess` file inside `public/` handles React Router routing — keep it there.
3. The frontend currently talks to `/api/*` on the same domain. If your API is on a different
   subdomain (e.g. `api.yourdomain.com`), you'll need to set `VITE_API_BASE_URL` before building.

---

## After Deployment

1. Visit `https://yourdomain.com/admin` and log in with your `ADMIN_PASSWORD`.
2. Go to **Settings** and fill in:
   - **Site URL** — your full domain (required for password reset emails)
   - **Crypto wallet addresses** — for the billing page
   - **Resend API key** — for password reset emails (free at resend.com)
3. Register your first user account and start using the platform.

---

## Troubleshooting

- **White screen / 404 on refresh** — make sure `.htaccess` is in `public/` and mod_rewrite is enabled.
- **API calls failing** — check `DATABASE_URL` and `SESSION_SECRET` are set correctly.
- **Password reset links go to wrong URL** — set `SITE_URL` in admin settings.
README

echo ""
echo "╔══════════════════════════════════════════════╗"
echo "║  ✓ Build complete!                           ║"
echo "║                                              ║"
echo "║  Output: ./cpanel-dist/                      ║"
echo "║  Read:   ./cpanel-dist/CPANEL-SETUP.md       ║"
echo "╚══════════════════════════════════════════════╝"
echo ""
