# IPTRM — Server Deployment Guide

This is a Python (Flask) web application backed by MySQL. It produces PDF/DOCX/
XLSX/HTML trademark-watch reports from Farsi PDF bulletins. Below is everything
required to run it on a Linux server.

--------------------------------------------------------------------------------
## 1. System requirements

- **OS:** Linux (Ubuntu/Debian recommended; any modern distro works)
- **Python:** 3.10 or newer (3.12 recommended)
- **MySQL:** 8.x (or MariaDB 10.5+), with a database + user created
- **System libraries for WeasyPrint** (PDF rendering) — this is the one part
  that needs OS packages, not just pip:

  Debian/Ubuntu:
  ```
  sudo apt-get update
  sudo apt-get install -y python3-venv python3-pip \
      libpango-1.0-0 libpangocairo-1.0-0 libcairo2 \
      libgdk-pixbuf-2.0-0 libffi-dev shared-mime-info \
      fonts-dejavu fonts-noto-core fonts-noto-cjk
  ```
  - `libpango*/libcairo*/libgdk-pixbuf*` — WeasyPrint's rendering backend
  - `fonts-noto-core` — Arabic/Farsi glyphs in PDFs
  - `fonts-noto-cjk` — Chinese glyphs in PDFs
  - `poppler-utils` is optional (only if you want server-side PDF->image)

  RHEL/CentOS/AlmaLinux:
  ```
  sudo dnf install -y python3 python3-pip \
      pango cairo gdk-pixbuf2 libffi google-noto-sans-fonts \
      google-noto-sans-cjk-fonts google-noto-naskh-arabic-fonts
  ```

If you deploy with **Docker** instead (see §6), you do NOT need to install any of
the above on the host — the image bundles them.

--------------------------------------------------------------------------------
## 2. Database setup

Create the database and user in MySQL:
```sql
CREATE DATABASE iptrm CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'iptrm'@'localhost' IDENTIFIED BY 'your-strong-password';
GRANT ALL PRIVILEGES ON iptrm.* TO 'iptrm'@'localhost';
FLUSH PRIVILEGES;
```
Tables are created automatically on first run. (A reference `schema.sql` is
included if you prefer to create them manually.)

--------------------------------------------------------------------------------
## 3. Install the application

```
unzip iptrm.zip -d iptrm && cd iptrm
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

--------------------------------------------------------------------------------
## 4. Configure (environment variables)

Copy `.env.example` to `.env` and fill it in. The app reads these from the
environment. Key values:

```
SECRET_KEY=<a long random string>          # REQUIRED in production (signs sessions)
USE_SQLITE=0                                # 0 = use MySQL
DB_USER=iptrm
DB_PASS=your-strong-password
DB_HOST=localhost
DB_NAME=iptrm

# SMTP for sending reports/invoices
SMTP_HOST=smtp.yourprovider.com
SMTP_PORT=587
SMTP_USER=...
SMTP_PASS=...
SMTP_FROM=reports@yourdomain.com
SMTP_USE_TLS=1

# First admin account (seeded on first run only)
ADMIN_USER=admin
ADMIN_PASSWORD=change-this-immediately

# Optional: auto-translation/transliteration (English/Chinese/Arabic)
ANTHROPIC_API_KEY=                          # leave blank to translate manually
ANTHROPIC_TRANSLATE_MODEL=claude-3-5-haiku-20241022
```

Generate a SECRET_KEY:  `python3 -c "import secrets; print(secrets.token_hex(32))"`

To load the .env into the environment before starting (simple approach):
```
set -a; source .env; set +a
```
(or use a process manager / systemd `EnvironmentFile=`, see §5).

--------------------------------------------------------------------------------
## 5. Run in production (gunicorn + nginx + systemd)

**Gunicorn** (the WSGI server, already in requirements):
```
gunicorn -w 3 -b 127.0.0.1:5000 --timeout 180 run:app
```
`run:app` is the entry point (`run.py` calls `init_db()` then exposes `app`).
`--timeout 180` gives headroom for large (200+ file) uploads.

**systemd unit** (`/etc/systemd/system/iptrm.service`):
```
[Unit]
Description=IPTRM
After=network.target mysql.service

[Service]
User=www-data
WorkingDirectory=/opt/iptrm
EnvironmentFile=/opt/iptrm/.env
ExecStart=/opt/iptrm/venv/bin/gunicorn -w 3 -b 127.0.0.1:5000 --timeout 180 run:app
Restart=always

[Install]
WantedBy=multi-user.target
```
```
sudo systemctl enable --now iptrm
```

**nginx** in front (TLS + larger upload body):
```
server {
    listen 443 ssl;
    server_name watch.yourdomain.com;
    ssl_certificate     /etc/letsencrypt/live/.../fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/.../privkey.pem;

    client_max_body_size 600M;            # uploads can be large
    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 180s;
    }
}
```
Get a free TLS cert with `certbot --nginx`.

--------------------------------------------------------------------------------
## 6. Alternative: Docker (bundles all system libs)

```
cp .env.example .env     # edit values
docker compose up --build -d
```
`docker-compose.yml` runs the app plus a MySQL 8 container. The Dockerfile
installs the Pango/Cairo/font libraries for you, so the host needs only Docker.

--------------------------------------------------------------------------------
## 7. First login & hardening checklist

1. Visit the site, log in as `ADMIN_USER` / `ADMIN_PASSWORD`.
2. **Change the admin password immediately** (top-right account page).
3. Confirm `SECRET_KEY` is a strong random value (sessions are signed with it).
4. Serve only over HTTPS (nginx + certbot above).
5. Create additional admin/viewer users under **Users**.
6. Daily uploads, review/edit, scan for conflicts, then send to subscribers.

Recommended (not yet built-in) for a public commercial deployment:
- login rate-limiting (e.g. nginx `limit_req` or fail2ban)
- regular `mysqldump` backups of the database and the `uploads/` directory
- CSRF protection if you expose this beyond a trusted admin group

--------------------------------------------------------------------------------
## 8. What persists on disk

- **MySQL** — all records (issues, applications, transliterations, translations,
  subscribers, invoices, watchlists, alerts, users, email logs).
- **`uploads/`** — the original source PDFs and extracted mark images. Back this
  up alongside the database; reports link to these source files.
