# 🚀 Deployment Guide — HMG ACADEMY CLASS DECK v9

This guide takes you from a fresh clone to a production deployment on **free-tier services**. We recommend **Cloudflare Pages** for the best free experience (free SSL, free CDN, free Workers for the optional signaling fallback).

---

## Table of Contents

1. [Quick start (local development)](#1-quick-start)
2. [Deploy to Cloudflare Pages (recommended)](#2-deploy-to-cloudflare-pages)
3. [Deploy to GitHub Pages](#3-deploy-to-github-pages)
4. [Deploy to Netlify / Vercel](#4-deploy-to-netlify--vercel)
5. [Deploy to your own server (any static host)](#5-deploy-to-your-own-server)
6. [Optional: free Cloudflare Worker for central revocation + signaling](#6-optional-cloudflare-worker)
7. [Optional: change the AUTH_SECRET per deployment](#7-change-auth_secret)
8. [Custom domain / multi-tenant](#8-custom-domain--multi-tenant)
9. [Verification checklist](#9-verification-checklist)
10. [Rollback](#10-rollback)

---

## 1. Quick start

```bash
git clone https://github.com/hmgacademyhub/hmgacademyclassdeck.git
cd hmgacademyclassdeck
python3 -m http.server 8080
# → open http://localhost:8080
```

You can also use any static-file server:
```bash
npx serve .
# or
php -S localhost:8080
```

> **No build step.** Everything is plain HTML/CSS/JS.

---

## 2. Deploy to Cloudflare Pages (recommended — 100% free)

### 2.1 One-time setup

1. Sign up / log in at <https://dash.cloudflare.com> (free tier, no card).
2. Click **Workers & Pages → Create application → Pages → Connect to Git**.
3. Pick your GitHub repo (`hmgacademyhub/hmgacademyclassdeck`).
4. **Build settings:**
   - **Framework preset:** None
   - **Build command:** *(leave empty)*
   - **Build output directory:** `/` (or `.`)
5. Click **Save and Deploy**. The first build takes ~30 seconds.
6. After deploy, you'll get a URL like `https://hmgacademyclassdeck.pages.dev`.

### 2.2 Headers

The repo includes a `_headers` file. Cloudflare Pages reads it automatically.

### 2.3 Verify

1. Open `https://hmgacademyclassdeck.pages.dev/` → install the PWA.
2. Open `teach.html` → sign up → start a class.
3. Open `join.html` on another device → enter the room code.
4. Done!

### 2.4 Cache invalidation

Service-worker cache is keyed on `CACHE_VERSION` in `sw.js`. To force all users to refresh:

1. Edit `sw.js` → bump `CACHE_VERSION` (e.g. `v9.0.0` → `v9.0.1`).
2. `git commit && git push`. Cloudflare Pages auto-deploys in ~30 s.
3. Users get the new app next time they reload.

---

## 3. Deploy to GitHub Pages

1. Push your repo to GitHub.
2. Settings → Pages → Source: **Deploy from a branch**, Branch: `main`, folder: `/` (root).
3. Wait ~2 min → your site is at `https://<user>.github.io/<repo>/`.
4. Open `https://<user>.github.io/<repo>/index.html`.

> GitHub Pages does **not** read `_headers` natively. CSP will be loose, but the app still works.

---

## 4. Deploy to Netlify / Vercel

Both work with the same settings:

| Field | Value |
|---|---|
| Build command | *(empty)* |
| Output directory | `/` |

Netlify reads `_headers` natively. Vercel reads `vercel.json` (not shipped — only `_headers`).

---

## 5. Deploy to your own server

Any static-file server works. The only requirement is HTTPS (so WebRTC + service workers + getUserMedia work).

```nginx
# /etc/nginx/sites-enabled/classdeck.conf
server {
  listen 443 ssl http2;
  server_name class.your-school.org;
  root /var/www/classdeck;
  index index.html;
  include /var/www/classdeck/_headers; # custom map → see below
  ...
}
```

Convert `_headers` to nginx syntax. Or use Caddy:
```
class.your-school.org {
  root * /var/www/classdeck
  header {
    X-Frame-Options "SAMEORIGIN"
    Content-Security-Policy "default-src 'self'; ..."
  }
  file_server
}
```

---

## 6. Optional: Cloudflare Worker for central revocation + signaling

The PWA works **fully offline** without any server. But for production you may want:
* **Central revocation** — push a key to `revoked.json` and have every install block it within 30 min.
* **Optional signaling fallback** — if PeerJS cloud is blocked on a school's firewall.

Both can be served by a free-tier Cloudflare Worker:

```js
// workers/hmg-revoker/src/index.js
export default {
  async fetch(req, env) {
    const url = new URL(req.url);
    if (url.pathname === "/revoke") {
      // pull from KV / R2 / GitHub raw — whichever you prefer
      return new Response(JSON.stringify({
        keys: ["HMG-202612-ABCDEFGHIJ"],
        blockedEmails: [],
        minTrialBuild: 9
      }), { headers: { "content-type": "application/json", "cache-control": "no-store" } });
    }
    return new Response("Not found", { status: 404 });
  }
};
```

Then edit `js/auth.js` and set:

```js
const HMG_SIGNALING_URL = "https://hmg-revoker.<your-subdomain>.workers.dev";
```

Deploy:
```bash
npm install -g wrangler
wrangler deploy
```

Free tier: **100,000 requests/day** — more than enough.

---

## 7. Change AUTH_SECRET

The default secret is **per-deployment, generated on first run**. It is stored in `localStorage["hmgcd_auth_secret"]` and pinned to that deployment.

For maximum security on a shared device (e.g. school tablets reused by many teachers), you can pre-pin a secret. This means the secret survives localStorage wipes but only if you distribute a special bootstrap page.

**Recommended:** leave the default behaviour. Each teacher gets a unique secret on first use, and the secret never leaves the browser.

---

## 8. Custom domain / multi-tenant

To brand the deployment for a school:

```
https://classdesk.example.org/?school=Gracefield-Academy
```

The title bar of `teach.html` will become `Teacher Studio · Gracefield-Academy · HMG ClassDeck`. The recording watermark (planned v9.1) will also use the school name.

For a fully white-labelled domain:

1. Buy a domain (or use a subdomain of your school's existing one).
2. In Cloudflare Pages → Custom domains → add it.
3. Optional: edit `index.html` → brand section to replace HMG ACADEMY logo + founder text.

---

## 9. Verification checklist

After deploying, verify each item:

| ✅ | Check |
|---|---|
| ☐ | `https://<your-domain>/index.html` loads and the PWA install button appears |
| ☐ | Service worker registers (DevTools → Application → Service Workers) |
| ☐ | `teach.html` → sign up with a test email → trial starts |
| ☐ | Open `join.html` on another device (or incognito) → enter room code → connects |
| ☐ | Whiteboard strokes appear on the student screen (or composite stream) |
| ☐ | Student chat message reaches the teacher |
| ☐ | Behaviour point award shows on student screen |
| ☐ | Open dashboard.html → create assignment → grade → CSV export downloads |
| ☐ | Open parent.html → enter parent code → report renders |
| ☐ | Open standards.html → 16 standards visible → export CSV downloads |
| ☐ | Switch language in landing page top-right → UI re-renders |
| ☐ | Disable network → all previously visited pages still load |

---

## 10. Rollback

If a deploy breaks things:

1. Cloudflare Pages → your project → **Deployments** → click the previous green build → **Rollback**.
2. Or `git revert HEAD && git push` to roll forward again.

---

## 11. Operational notes

* **Backups:** none required. All data lives in each user's browser IndexedDB.
* **Scaling:** unlimited — Cloudflare Pages free tier is more than enough for any single school.
* **Support:** file an issue on GitHub. Community volunteers reply within 1–3 days.
* **License:** MIT — fork freely.

---

## 12. Troubleshooting

| Problem | Fix |
|---|---|
| Whiteboard strokes not appearing on student screen | Both must be on the same network. If behind a corporate firewall, use the **QR/URL** backup join instead of PeerJS cloud. |
| Service worker not registering | Make sure you're on **HTTPS** (or `http://localhost`). |
| Camera blocked on student device | The student must grant permission **on each new device** — this is a browser security feature, not a bug. |
| License key not activating | Ensure the teacher's name in the admin tool matches exactly what they typed at sign-up (case-insensitive). |
| `revoked.json` not updating | Cloudflare Pages caches `_headers`-ignored files for 5 min. Add `Cache-Control: no-cache` to the file in `_headers`. |
| PWA install prompt not showing | Chrome hides it if you visit more than once within a week. Use the browser's "Install" menu instead. |

---

## 🎉 You're done!

Your HMG ACADEMY CLASS DECK v9 Enterprise Edition is live. Visit your URL and share it with teachers everywhere. 🧑‍🏫
