#!/usr/bin/env bash
# Backup for the n8n Compose stack of lesson AUT-204-L01. Run from the folder that holds compose.yaml.
# Produces: readable workflow files (for Git), ENCRYPTED credentials, a PostgreSQL dump and checksums.
# It never exports decrypted credentials and never copies the encryption key: back that up separately.
set -euo pipefail
STAMP="$(date +%Y%m%d-%H%M%S)"
DEST="${BACKUP_DIR:-./backups}/${STAMP}"
TMP=/home/node/.n8n/backup-tmp
mkdir -p "$DEST"

docker compose exec -T -u node n8n rm -rf "$TMP"
docker compose exec -T -u node n8n n8n export:workflow --backup --output="$TMP/workflows/"
docker compose exec -T -u node n8n n8n export:credentials --all --separate --output="$TMP/credentials/"
docker compose cp "n8n:$TMP/." "$DEST/n8n-export/"
docker compose exec -T -u node n8n rm -rf "$TMP"

docker compose exec -T postgres pg_dump -U n8n -d n8n --format=custom > "$DEST/n8n-db.dump"

( cd "$DEST" && find . -type f ! -name SHA256SUMS -exec sha256sum {} + > SHA256SUMS )
echo "backup written to $DEST"
echo "reminder: the encryption key is NOT in this folder; without it the credentials cannot be decrypted"
