# Experiments Database — Backup

## Location
```
/home/sam/synology/Backups/Experiments-DB-Backup/
├── daily/          ← up to 5 change-triggered daily backups
├── weekly/         ← up to 2 unconditional weekly backups
├── .last_backup_state   ← DB fingerprint from last backup run
└── backup.log      ← all run output
```

## Scripts
```
scripts/
├── backup.sh       ← main backup script
└── setup_cron.sh   ← installs / updates cron entries (idempotent)
```

## Schedule
| Cron | Mode | Behaviour |
|------|------|-----------|
| `0 2 * * *` (daily 02:00) | `daily` | Compares DB fingerprint; skips if nothing changed |
| `0 3 * * 0` (Sunday 03:00) | `weekly` | Always dumps; ignores fingerprint |

To re-install cron entries after a path change:
```bash
./scripts/setup_cron.sh
```

## Backup Format
Files are `pg_dump --format=custom --compress=9` (`.pgdump`).

**Restore a backup:**
```bash
# Restore into a running container
docker exec -i experiments_postgres pg_restore \
  -U expuser -d experiments_db --clean \
  < /home/sam/synology/Backups/Experiments-DB-Backup/daily/<file>.pgdump

# Or restore to a fresh database
docker exec -i experiments_postgres createdb -U expuser experiments_db_restore
docker exec -i experiments_postgres pg_restore \
  -U expuser -d experiments_db_restore \
  < /path/to/file.pgdump
```

## Change Detection
The daily run fingerprints the database as:
```
<experiments count>,<animals count>,<daily_statuses count>,
<daily_analyses count>,<session_files count>,<latest audit_log timestamp>
```
Any insert, update, or delete on any table shifts this string and triggers a backup.

## Retention Policy
| Type | Keep |
|------|------|
| Daily | 5 most recent |
| Weekly | 2 most recent |

Older files are automatically deleted after each successful dump.

## Manual Run
```bash
# Force a backup right now (ignores change detection)
./scripts/backup.sh weekly

# Run change-detect check manually
./scripts/backup.sh daily
```

## Verify Cron Is Installed
```bash
crontab -l | grep ExpDB
```
