#!/usr/bin/env bash
# Build a clean cPanel / shared-hosting deploy ZIP (run from project root).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
VERSION="$(tr -d '[:space:]' < "$ROOT/VERSION")"
OUT_DIR="$ROOT/dist"
STAGE="$OUT_DIR/stage"
NAME="Academy-LMS-v${VERSION}-cPanel"

rm -rf "$STAGE" "$OUT_DIR/${NAME}.zip"
mkdir -p "$STAGE/Documentation" "$STAGE/Main Files"

# Admin how-to guide into Documentation
mkdir -p "$ROOT/documentation"
cp -f "$ROOT/static/docs/admin-guide.html" "$ROOT/documentation/admin-guide.html" 2>/dev/null || true

# Docs
cp -R "$ROOT/documentation/." "$STAGE/Documentation/"

# Main files via rsync-like copy
rsync -a \
  --exclude 'venv' \
  --exclude '.venv' \
  --exclude '.env' \
  --exclude 'dist' \
  --exclude 'storage/installed' \
  --exclude '__pycache__' \
  --exclude '*.pyc' \
  --exclude '.git' \
  --exclude 'db.sqlite3' \
  --exclude '*.sqlite3' \
  --exclude '.DS_Store' \
  --exclude '.cursor' \
  --exclude 'logs/*.log' \
  --exclude 'staticfiles' \
  --exclude 'media/payment_proofs' \
  --exclude 'media/profile_pictures' \
  --exclude 'media/course_thumbnails' \
  --exclude 'media/course_certificates' \
  --exclude 'media/course_badges' \
  --exclude 'media/practical_submissions' \
  --exclude 'media/project_submissions' \
  --exclude 'media/project_screenshots' \
  --exclude 'media/module_pdfs' \
  --exclude 'media/certificates' \
  --exclude 'media/Logo/*' \
  --exclude 'agent-transcripts' \
  "$ROOT/" "$STAGE/Main Files/"

# Keep Logo folder empty-ready
mkdir -p "$STAGE/Main Files/media/Logo"
touch "$STAGE/Main Files/media/Logo/.gitkeep"

# Ensure empty storage (no lock) — fresh cPanel installs run /install/
mkdir -p "$STAGE/Main Files/storage"
rm -f "$STAGE/Main Files/storage/installed"
touch "$STAGE/Main Files/storage/.gitkeep"

# Empty runtime dirs that must exist on upload
mkdir -p "$STAGE/Main Files/logs" "$STAGE/Main Files/staticfiles"
touch "$STAGE/Main Files/logs/.gitkeep"
touch "$STAGE/Main Files/staticfiles/.gitkeep"

# Ensure admin guide ships inside Main Files too
mkdir -p "$STAGE/Main Files/static/docs" "$STAGE/Main Files/documentation"
cp -f "$ROOT/static/docs/admin-guide.html" "$STAGE/Main Files/static/docs/admin-guide.html"
cp -f "$ROOT/static/docs/admin-guide.html" "$STAGE/Main Files/documentation/admin-guide.html"
cp -f "$ROOT/static/docs/admin-guide.html" "$STAGE/Documentation/admin-guide.html"

cp "$ROOT/README.md" "$STAGE/Main Files/README.md"

# ---------------------------------------------------------------------------
# START-HERE.html — open this first after unzipping
# ---------------------------------------------------------------------------
cat > "$STAGE/START-HERE.html" << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>START HERE — cPanel Deploy</title>
  <style>
    body{font-family:system-ui,sans-serif;max-width:820px;margin:2rem auto;padding:0 1rem;line-height:1.55;color:#0f172a}
    h1{font-size:1.75rem} h2{font-size:1.2rem;margin-top:1.75rem;border-bottom:1px solid #e2e8f0;padding-bottom:.4rem}
    .box{background:#eff6ff;border-left:4px solid #2563eb;padding:1rem 1.1rem;border-radius:.5rem;margin:1rem 0}
    .warn{background:#fffbeb;border-left-color:#d97706}
    .ok{background:#ecfdf5;border-left-color:#059669}
    code,kbd{background:#e2e8f0;padding:.1rem .35rem;border-radius:.3rem;font-size:.9em}
    ol li{margin:.45rem 0} a{color:#1d4ed8}
  </style>
</head>
<body>
  <h1>TSN Digital Academy — Deploy on cPanel</h1>
  <p>Follow these steps on <strong>shared hosting</strong> with cPanel <em>Setup Python App</em>.</p>

  <div class="box">
    <strong>ZIP contents</strong>
    <ul>
      <li><code>START-HERE.html</code> — this file</li>
      <li><code>CPANEL-DEPLOY.txt</code> — same steps as plain text</li>
      <li><code>Main Files/</code> — upload <em>everything inside</em> this folder</li>
      <li><code>Documentation/</code> — docs + full Admin Guide (HTML)</li>
    </ul>
  </div>

  <h2>Step 1 — Create MySQL database (recommended)</h2>
  <ol>
    <li>cPanel → <strong>MySQL® Databases</strong></li>
    <li>Create a database (e.g. <code>academy</code>)</li>
    <li>Create a MySQL user with a strong password</li>
    <li>Add the user to the database with <strong>ALL PRIVILEGES</strong></li>
    <li>Note the full names (often <code>cpaneluser_dbname</code> / <code>cpaneluser_dbuser</code>)</li>
  </ol>

  <h2>Step 2 — Create Python App</h2>
  <ol>
    <li>cPanel → <strong>Setup Python App</strong> → Create Application</li>
    <li>Python version: <strong>3.10+</strong> (3.11 or 3.12 if available)</li>
    <li>Application root: e.g. <code>academy</code> (folder where files will live)</li>
    <li>Application URL: your domain or subdomain</li>
    <li>Application startup file: <code>passenger_wsgi.py</code></li>
    <li>Application Entry point: <code>application</code></li>
    <li>Click <strong>Create</strong></li>
  </ol>

  <h2>Step 3 — Upload files</h2>
  <ol>
    <li>Open File Manager → go into the Application root folder</li>
    <li>Upload <strong>all contents of <code>Main Files/</code></strong> (not the folder name itself)</li>
    <li>You should see <code>manage.py</code>, <code>passenger_wsgi.py</code>, <code>apps/</code>, <code>config/</code>, etc.</li>
    <li>Do <strong>not</strong> upload a local <code>.env</code>, <code>venv/</code>, or <code>db.sqlite3</code></li>
  </ol>

  <h2>Step 4 — Install packages</h2>
  <ol>
    <li>In Setup Python App, copy the command under <strong>Enter to the virtual environment</strong></li>
    <li>Open <strong>Terminal</strong> (or SSH), paste that command, press Enter</li>
    <li>Run:
      <pre>cd ~/academy
pip install -r requirements.txt
python manage.py collectstatic --noinput</pre>
      (Replace <code>~/academy</code> with your real application root.)
    </li>
  </ol>

  <h2>Step 5 — Restart &amp; install</h2>
  <ol>
    <li>Back in Setup Python App → <strong>Restart</strong></li>
    <li>Open <code>https://YOUR-DOMAIN/install/</code></li>
    <li>Complete the wizard (choose MySQL and enter the DB details from Step 1)</li>
    <li>Log in with the admin account you created in the installer</li>
  </ol>

  <div class="box ok">
    <strong>After install</strong>
    <ol>
      <li>Dashboard → <strong>Admin Guide</strong> (full how-to for every module)</li>
      <li><strong>Academy Settings</strong> → branding, payments, Email/SMTP</li>
      <li>Create a course → import questions → enable Free skill check if needed</li>
    </ol>
  </div>

  <div class="box warn">
    <strong>If the site shows an error after upload</strong>
    <ul>
      <li>Confirm <code>passenger_wsgi.py</code> is the startup file and Entry point is <code>application</code></li>
      <li>Confirm <code>pip install -r requirements.txt</code> finished without errors</li>
      <li>Folders <code>media/</code>, <code>logs/</code>, <code>storage/</code>, <code>staticfiles/</code> must be writable (755/775)</li>
      <li>Restart the Python app again</li>
    </ul>
  </div>

  <p>More detail: <a href="CPANEL-DEPLOY.txt">CPANEL-DEPLOY.txt</a> ·
     <a href="Documentation/index.html">Documentation</a> ·
     <a href="Documentation/admin-guide.html">Admin Guide</a></p>
</body>
</html>
EOF

# ---------------------------------------------------------------------------
# CPANEL-DEPLOY.txt
# ---------------------------------------------------------------------------
cat > "$STAGE/CPANEL-DEPLOY.txt" << 'EOF'
================================================================================
TSN Digital Academy — cPanel shared hosting deploy guide
================================================================================

WHAT TO UPLOAD
--------------
Upload everything INSIDE the "Main Files/" folder into your Python App root
(the folder that contains manage.py after upload).

Do NOT upload: venv/, .env, db.sqlite3, or this ZIP's Documentation/ folder
into the app root (Documentation is for you to read offline).


BEFORE YOU START
----------------
1) Create a MySQL database + user in cPanel → MySQL® Databases
   (All Privileges). Write down: DB name, user, password, host (usually
   localhost).

2) cPanel → Setup Python App → Create:
   - Python 3.10+ (prefer 3.11/3.12)
   - Application root = e.g. academy
   - Application URL = your domain/subdomain
   - Startup file = passenger_wsgi.py
   - Entry point = application


INSTALL PACKAGES
----------------
Copy the "Enter to the virtual environment" command from Setup Python App,
open Terminal/SSH, then:

  cd ~/academy          # your application root
  pip install -r requirements.txt
  python manage.py collectstatic --noinput

Restart the Python App in cPanel.


WEB INSTALLER
-------------
Open:  https://YOUR-DOMAIN/install/

Choose MySQL, enter DB credentials, set academy name + admin login.
The installer writes .env, runs migrations, and creates your admin.


AFTER INSTALL
-------------
1) Log in → open Admin Guide from the dashboard sidebar
2) Academy Settings → Branding, Payments, Email/SMTP (send a test email)
3) Manage Courses → create/publish courses
4) Import verified questions (needed for exams + Free skill check)
5) Toggle "Enable Free skill check" per course under Growth & marketing


PERMISSIONS
-----------
These folders must be writable by the app:
  media/   logs/   storage/   staticfiles/


STATIC & MEDIA
--------------
- Static CSS/JS: WhiteNoise serves them after collectstatic
- Media uploads: Django serves /media/ by default (SERVE_MEDIA=True in .env)


COMMON PROBLEMS
---------------
- 500 error after deploy → restart app; check passenger_wsgi.py + pip install
- CSS missing → run collectstatic --noinput and restart
- /install/ loops or blocked → delete storage/installed only if you intend to
  reinstall (also reset DB if needed)
- Skill check error "need 12 verified questions" → import & verify questions


SUPPORT FILES IN THIS ZIP
-------------------------
START-HERE.html              — visual quick start (open in browser)
Documentation/index.html     — product documentation
Documentation/admin-guide.html — full admin how-to (every module)
Main Files/                  — application source
================================================================================
EOF

# Seller / packaging note
cp "$ROOT/PACKAGING.md" "$STAGE/README-SELLER.txt" 2>/dev/null || true

(
  cd "$STAGE"
  zip -r "$OUT_DIR/${NAME}.zip" . -x "*.DS_Store" -x "*/__pycache__/*" -x "*.pyc"
)

# Also keep a short alias name
cp -f "$OUT_DIR/${NAME}.zip" "$OUT_DIR/Academy-LMS-cPanel.zip"

echo ""
echo "Created:"
ls -lh "$OUT_DIR/${NAME}.zip" "$OUT_DIR/Academy-LMS-cPanel.zip"
echo ""
echo "Upload Academy-LMS-cPanel.zip (or ${NAME}.zip) to your PC, unzip,"
echo "then follow START-HERE.html"
