# Nightly database backups to S3

The application dumps its MySQL database once a night to Amazon S3 using
[spatie/laravel-backup](https://spatie.be/docs/laravel-backup). Everything is
configured in `config/backup.php` and scheduled in `routes/console.php`.

> **These archives contain the database only.**
> Uploaded photos and customer documents under `storage/app/` are not in them. A
> restore brings back every booking, enquiry and visa record, pointing at images
> and files that are gone. If that matters, cover `storage/app/` separately — see
> [Files are not covered](#files-are-not-covered).

## What runs, and when

Times are UTC, as everything in this application is. Bangladesh is UTC+6, so
these land between 01:30 and 03:00 local, when the site is quietest.

| Time (UTC) | Command | Purpose |
| --- | --- | --- |
| 19:30 | `backup:clean` | Prunes old archives, so a bucket at its size limit has room for tonight |
| 20:00 | `backup:run` | Dumps the database, gzips it, uploads to S3 |
| 21:00 | `backup:monitor` | Emails if the newest archive is over a day old or the bucket is oversized |

These ride on the scheduler cron that already runs `bookings:expire-unpaid`, so
there is nothing new to install on the server:

```
* * * * * cd /path/to/lets_tour_admin && php artisan schedule:run >> /dev/null 2>&1
```

**The monitor is the part that protects you.** A backup that stops — expired
keys, a full bucket, a deleted IAM user, `mysqldump` disappearing after a server
upgrade — is otherwise completely silent. Do not drop it from the schedule.

## Setup

### 1. The bucket

Create a private S3 bucket. Do not enable public access; the dump is the whole
customer database. Two settings worth turning on:

- **Versioning**, so an archive cannot be silently overwritten.
- A **lifecycle rule** to Glacier or Deep Archive past ~30 days, if cost matters
  more than restore speed. Database-only archives are small, so this may not be
  worth the complexity.

### 2. The IAM user

Create a dedicated user with programmatic access and only these actions, scoped
to that one bucket: `s3:PutObject`, `s3:GetObject`, `s3:DeleteObject`,
`s3:ListBucket`. `DeleteObject` is needed by `backup:clean`; without it archives
accumulate until the monitor complains about storage.

### 3. Environment

Add to the production `.env` (see `.env.example` for the annotated block):

```sh
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_DEFAULT_REGION=ap-southeast-1
AWS_BUCKET=lets-go-backups

BACKUP_DISK=s3
BACKUP_ARCHIVE_PASSWORD=...        # strongly recommended, see below
BACKUP_NOTIFICATION_EMAIL=         # optional, see below
BACKUP_MAX_STORAGE_MB=1000
```

Then refresh the cached configuration:

```sh
php artisan config:clear && php artisan config:cache
```

### 4. Verify before trusting it

```sh
php artisan backup:run          # writes a real archive to S3
php artisan backup:list         # should show the backup as reachable and healthy
```

`backup:list` reporting *Reachable* and *Healthy* is the only proof the
credentials, the bucket and the monitor all agree with each other.

## Encryption

`BACKUP_ARCHIVE_PASSWORD` encrypts the zip with AES-256. It is strongly
recommended: the dump holds customer names, phone numbers, addresses, passport
details and booking history, sitting in object storage.

**An encrypted archive cannot be restored without the password.** Store it
wherever the other production secrets live — not on the server it protects, and
not in this repository.

## Who gets told

Failures, unhealthy backups and successful runs are emailed. With
`BACKUP_NOTIFICATION_EMAIL` empty, alerts go to the same people the app already
emails about bookings and enquiries: every super admin, plus any addresses in
**Business Settings → Admin notification emails**. Set the variable to send them
somewhere else instead, comma-separated for several.

`App\Notifications\BackupNotifiable` handles this, and also applies the SMTP
account from Business Settings before sending — without that step an alert would
go out through whatever `.env` happens to say, which on this deployment is the
log file.

To stop the nightly "backup successful" mail and keep only the failures, remove
`BackupWasSuccessfulNotification`, `HealthyBackupWasFoundNotification` and
`CleanupWasSuccessfulNotification` from `notifications.notifications` in
`config/backup.php`. Consider keeping at least one success notification: silence
is also what a broken scheduler looks like.

## Retention

The default strategy, in `config/backup.php`:

- every backup for 7 days
- one a day for 16 days
- one a week for 8 weeks
- one a month for 4 months
- one a year for 2 years

Past `BACKUP_MAX_STORAGE_MB`, the oldest archives are deleted until the total
fits. That threshold is deliberately the same number the monitor's storage health
check uses — cleanup that tolerated more than the monitor does would alert every
night. 1000 MB is generous for gzipped dumps; raise it once the database grows,
rather than letting cleanup quietly eat the history.

## Files are not covered

`config/backup.php` sets `source.files.include` to an empty array, so the archive
contains one entry: `db-dumps/mysql-<database>.sql.gz`.

What that leaves unprotected:

- `storage/app/public` — every uploaded photo: ships, cabins, tour packages,
  destinations, blogs, gallery.
- `storage/app/private` — customer documents and visa submissions.

Neither can be regenerated. Options, roughly in order of effort:

- **A provider snapshot** of the server volume, if the host offers one. Simplest,
  and covers everything else on the box too.
- **`aws s3 sync storage/app s3://bucket/uploads`** on its own cron. Cheap, and
  uploads change rarely enough that each run transfers almost nothing.
- **Put the files back in this backup**: set `include` to `[base_path()]` in
  `config/backup.php`. The exclusion list beneath it is already written for that
  case. Expect archives to go from tens of KB to the size of the uploads
  directory, every night, so raise `BACKUP_MAX_STORAGE_MB` with it.

## Restoring

There is no restore command; a restore is deliberate and manual.

1. Download the archive from S3 and unzip it (with the password, if set).
2. Import `db-dumps/mysql-*.sql.gz` into a **new, empty** database — never over a
   live one you have not finished inspecting:
   ```sh
   gunzip -c mysql-tms.sql.gz | mysql -u user -p restored_db
   ```
3. Point `.env` at it, then `php artisan config:cache` and clear the app cache.
4. Uploaded files come from whatever covers `storage/app/` (above), not from this
   archive. Records whose images are missing will render with broken images
   rather than fail.

## Requirements on the server

- `ext-zip` for PHP.
- The `mysqldump` binary on `PATH`. If it is somewhere unusual, add a `dump` key
  to the `mysql` connection in `config/database.php`:
  `'dump' => ['dump_binary_path' => '/usr/bin/']`.
- A little free space in `storage/app/backup-temp` while the archive is built,
  before it is uploaded and removed.
