# Deploying on your own server (first time from git, then every update)

For the setup you already have: **Nota running from an unzipped folder** (your
"app folder", e.g. `~/nfce-app`), your **existing PostgreSQL 16** (`postgres16`,
database `nfce_app`, with data), **playwright-server** on the LAN, and Docker +
Docker Compose on the server. Everything runs **on the server**, in a terminal.

What you do *not* need:
- **SeaweedFS** — Nota keeps nothing in object storage (later it can be the
  destination for off-machine backups; see the end).
- **Your own Redis** — Nota doesn't use Redis today. The compose file starts a
  tiny `nfce-app-redis` container as before; leave it.

Time: ~20 minutes. Downtime: from stopping the old app (step 3) until the new
one passes its health check (step 5).

Sections 1–6 are the first time only. After that, every update is section 8:
`cd` into the folder and run one script.

---

## 1. Note where you are, and back up the database

```bash
cd ~/nfce-app                      # your app folder — adjust the path
docker ps --format '{{.Names}}\t{{.Status}}' | grep -i nfce
docker exec nfce-app alembic current
```

Expect **`0020 (head)`**. If it shows something else, stop and ask before
continuing.

Your own database backup (the update script also takes one; this one is yours
to keep). Replace `llmproxy`/`nfce_app` if your user/database differ:

```bash
mkdir -p ~/nota-backups
docker exec postgres16 pg_dump -U llmproxy -d nfce_app --format=custom --no-owner \
  > ~/nota-backups/nfce_app_before_git_$(date +%Y%m%d).dump
ls -lh ~/nota-backups/             # must not be 0 bytes
```

## 2. Give the server read access to the repository (once)

The repository is private. A **deploy key** is read-only and limited to this
one repository:

```bash
ssh-keygen -t ed25519 -f ~/.ssh/nota_deploy -N "" -C "nota-server"
cat ~/.ssh/nota_deploy.pub
```

On GitHub: **RaafelBR/nfce-app → Settings → Deploy keys → Add deploy key** —
paste it, leave "Allow write access" **off**. Then:

```bash
cat >> ~/.ssh/config <<'EOF'
Host github-nota
  HostName github.com
  User git
  IdentityFile ~/.ssh/nota_deploy
  IdentitiesOnly yes
EOF
ssh -T github-nota                 # "Hi RaafelBR/nfce-app! You've successfully authenticated..."
```

## 3. Turn your app folder into a git checkout (in place)

**Is it already one?** Run `git -C ~/nfce-app status`. If that works, skip to
the box at the end of this section.

Otherwise:

```bash
cd ~/nfce-app

# a) stop the old stack WITH THE OLD compose file (before git replaces it).
#    Only containers go away; the database lives in postgres16.
docker compose down

# b) keep a complete copy of the old folder — this is your way back
cp -a ~/nfce-app ~/nfce-app-before-git

# c) make it a checkout of main; tracked files are replaced by the repo's
#    versions. .env and backups/ are ignored by git, so they are kept.
git init -b main
git remote add origin github-nota:RaafelBR/nfce-app.git
git fetch origin main
git checkout -f -B main origin/main
git branch --set-upstream-to=origin/main main
git log --oneline -1
```

Files that existed in the old folder but are not in the repository are left
alone, as "untracked". Look at them:

```bash
git status --short                 # lines starting with ?? are untracked
```

Leftovers from the old zip are harmless, except anything inside `app/`,
`alembic/` or `static/`: those folders are copied into the image. To remove only
untracked files (`.env`, `backups/` and other ignored files are never touched),
preview first and then confirm:

```bash
git clean -n -d                    # preview — nothing deleted
git clean -f -d                    # delete what the preview listed
```

> **Already a git checkout?** Then:
> ```bash
> cd ~/nfce-app
> docker compose down              # first time only — see the note above
> git remote -v                    # should point at RaafelBR/nfce-app
> git pull --ff-only origin main
> ```

## 4. Configuration (`.env`)

Your `.env` stayed in place. It already has your real `DATABASE_URL`,
`JWT_SECRET` (**keep the same one**, or every login and token stops working),
`PLAYWRIGHT_WS_ENDPOINT` and LLM settings. Add the newer settings at the end
(`nano .env`). All are optional; the defaults reproduce the old behaviour:

```dotenv
# The Docker network postgres16 is on (the old compose file hard-coded this)
HOMELAB_NETWORK=homelab_default
HOMELAB_NETWORK_EXTERNAL=true
APP_PORT=8010

# Leave empty until Nota has its HTTPS address; then e.g. https://nota.example.com
PUBLIC_BASE_URL=

# Once a reverse proxy/Authelia is in front (docs/DEPLOY_AUTHELIA.md):
#APP_BIND=127.0.0.1
#FORWARDED_ALLOW_IPS=172.16.0.0/12
```

Not sure about the network name?
`docker inspect postgres16 --format '{{json .NetworkSettings.Networks}}'`

## 5. First deploy — with the safe update script

```bash
cd ~/nfce-app
scripts/safe-update.sh --dry-run          # shows the plan; changes nothing
scripts/safe-update.sh --force --no-pull  # the real thing
```

(`--no-pull`: you just checked out the latest `main`. `--force`: there's no
running version in this checkout to compare with yet.) In order, it:

1. dumps the database into `./backups/` and checks the dump reads back —
   if that fails it stops **before changing anything**;
2. builds the new image;
3. runs `alembic upgrade head` in a one-off container: **0020 → 0024** (new
   tables/columns only — nothing existing is changed or deleted);
4. starts `nfce-app` + `nfce-app-redis` and waits for
   `http://127.0.0.1:8010/health/ready` (app up **and** database reachable).

It ends with `Update OK — <commit>, schema 0024, healthy.`

## 6. Check it

```bash
curl -s http://127.0.0.1:8010/health/ready     # {"status":"ok","database":"ok"}
docker exec nfce-app alembic current           # 0024 (head)
docker compose ps                              # nfce-app ... (healthy)
```

Open `http://<server-ip>:8010/` and log in as usual: same accounts, same data.
Then:
- **Chrome extension:** `chrome://extensions` → Nota → reload. One file was
  added to it; its settings are kept.
- Your existing **cron** calls (due-date reminders, etc.) need no change.

## 7. If something goes wrong

**During the script:** it rolls itself back. On this *first* run there is no
earlier version in this checkout to return to, so read its last lines and use
the steps below.

**Going back to the old app.** The old app runs `alembic upgrade head` on
start and doesn't know revisions 0021–0024, so it would crash-loop on the
upgraded database. Downgrade the schema first, **with the new image** (only it
has those migration files), then start the copy you made in step 3b:

```bash
cd ~/nfce-app
docker compose stop nfce-app
docker compose run --rm --no-deps nfce-app alembic downgrade 0020
docker compose down
cd ~/nfce-app-before-git && docker compose up -d
```

Downgrading to 0020 drops only what this update added: forecast scenarios,
pairing codes, the device/token list, and the Tandoor/pairing settings columns.

**Last resort: restore the dump from step 1.** This replaces the whole database
with the copy taken before you started; anything recorded since is lost:

```bash
docker exec -i postgres16 pg_restore -U llmproxy -d nfce_app --clean --if-exists --no-owner \
  < ~/nota-backups/nfce_app_before_git_YYYYMMDD.dump
```

## 8. Every update from now on

When a change has been merged into `main`:

```bash
cd ~/nfce-app
scripts/safe-update.sh
```

That's the whole thing: **don't run `git pull` yourself**, the script does it.
It fetches `main` (fast-forward only), backs up, builds, migrates, restarts and
health-checks. On any failure after the backup it **downgrades the schema,
returns the code to the previous commit, restores the previous image and
restarts it**, then exits with an error. With nothing new it says "Already up
to date and healthy" and does nothing. `./backups/` keeps the last 14 dumps
(`BACKUP_KEEP` in `.env`).

Rules for the folder:
- Don't edit tracked files in it. The script refuses to run on local changes,
  because rollback uses `git reset --hard`.
- Your own additions are fine: `.env`, `backups/`, a
  `docker-compose.override.yml`.

**Rehearse the rollback once**, while nothing is at stake. This forces a failed
health check on purpose: expect "Rolling back" and `exit=1`, then the app
healthy again:

```bash
HEALTH_URL=http://127.0.0.1:1/nope HEALTH_TIMEOUT=10 scripts/safe-update.sh --force --no-pull; echo "exit=$?"
curl -s http://127.0.0.1:8010/health/ready
```

## 9. Deploying somewhere else (from a bundle)

`scripts/make-bundle.sh` writes two files into `dist/`:

| File | What it is | Use it when |
| --- | --- | --- |
| `nota-<date>-<commit>.bundle` | the git repository with full history, in one file | **preferred**: the target gets a real checkout, so `safe-update.sh` works there |
| `nota-<date>-<commit>.tar.gz` | the source tree at that commit, without `.git` | the target must not have git; `safe-update.sh` won't work there |

Each comes with a `.sha256` checksum file.

```bash
cd ~/nfce-app && scripts/make-bundle.sh        # bundles main; pass a ref to bundle another one
```

On the other machine (Docker + Compose installed):

```bash
sha256sum -c nota-*.bundle.sha256
git clone nota-YYYYMMDD-abc1234.bundle nota && cd nota
cp .env.example .env && nano .env              # its own DATABASE_URL, JWT_SECRET, ...
```

Then pick one:
- **It has its own PostgreSQL:** use Mode A in `.env` and run
  `scripts/safe-update.sh --force --no-pull`.
- **Self-contained:** uncomment the "Mode B" block in `.env`. It adds
  PostgreSQL 16 via `COMPOSE_PROFILES=bundled`. Then run
  `scripts/safe-update.sh --force --no-pull`. An empty database gets every
  migration from 0001; register the first account in the web UI.

Later updates on that machine: either point it at GitHub
(`git remote set-url origin github-nota:RaafelBR/nfce-app.git`, plus a deploy
key there) and use plain `scripts/safe-update.sh`, or copy a newer bundle over
and run:

```bash
git pull --ff-only /path/to/newer.bundle main
scripts/safe-update.sh --force --no-pull
```

From the tarball instead, with no git: `tar xzf nota-*.tar.gz && cd nota`, edit
`.env` as above, then `docker compose up -d --build`. That runs no backup and
no rollback; migrations still run when the container starts.

## 10. After it's running

- **HTTPS + Authelia:** `docs/DEPLOY_AUTHELIA.md`. Then set `PUBLIC_BASE_URL`
  and `APP_BIND=127.0.0.1` in `.env` and run
  `scripts/safe-update.sh --force --no-pull` to apply.
- **Phones:** Configurações → Capturar no celular (needs the HTTPS address).
- **Checks still owed:** `docs/BACKLOG.md` → "Verification owed".
- **Backups off the machine:** dumps happen only when you update, and stay on
  this server. Scheduled backups are the top item in `docs/BACKLOG.md`;
  SeaweedFS (S3 API) is a natural destination.
- Once everything has run fine for a while, delete `~/nfce-app-before-git`.
