#!/usr/bin/env bash
#
# full backup of fflol (or another ao3 fork) to another LAN machine 
# via SSH using rsync and tarballs.
#
# Backs up: 1) a mysqldump of the database
#           2) a tarball of the Elasticsearch data directory
#           3) the entire app directory (code, config, uploaded files)
# Then pushes it all to a remote host with rsync, throttled to prevent
# using too much of the production machine of CPU, disk I/O or bandwidth.
#
# rsync only transfers deltas. Cron-friendly.
#
# REQUIREMENTS:
#   - passwordless SSH from THIS machine to the remote (ssh-copy-id once)
#   - rsync on both ends, docker running, ionice + nice (util-linux)
#
# ---------------------------------------------------------------------------

set -euo pipefail

############################ CONFIG (edit me) ##############################

# Where the AO3 directory exists on the server (the dir bind-mounted to /otwa)
APP_DIR="/home/YOU/ao3"

# The MariaDB/MySQL docker container name (`docker ps` to check)
DB_CONTAINER="db"

# Database credentials, match the docker-compose.yml / config/database.yml
DB_NAME="otwarchive_production"
DB_USER="root"
DB_PASS="change_me"

# Elasticsearch data directory on the host (the volume mounted into the
# es container). Set ES_DATA_DIR="" to skip the ES step.
ES_DATA_DIR="${APP_DIR}/es"

# Remote target. user@host must already accept this machine's SSH key.
REMOTE="you@backup-host"
REMOTE_BASE="/home/you/backups"          # parent dir on the remote

# Bandwidth cap for rsync, in KB/s, ~10 MB/s
# Raise it (e.g. 51200 = 50 MB/s) if yr machines are fast. Zoom zoom.
BW_LIMIT=10240

# How many days of *dump artifacts* to keep locally.
RETENTION_DAYS=30

############################################################################

TS="$(date +%Y%m%d_%H%M%S)"
TODAY="$(date +%Y%m%d)"
BACKUP_DIR="${APP_DIR}/backups"
REMOTE_DIR="${REMOTE_BASE}/${TODAY}-full"

mkdir -p "${BACKUP_DIR}"

echo "=== BACKUP TIME! ${TS} ==="

############################################################################
# Step 1: database dump
#
# Dump through the docker container rather than copying the raw data dir.
# Never rsync live InnoDB files (db/, mysql-data/) as they're root-owned
# and being written mid-copy.
############################################################################

DB_DUMP="${BACKUP_DIR}/db_${TS}.sql.gz"
echo "[1/3] mysqldump -> ${DB_DUMP}"
# nice -n 19: gzip runs at lowest CPU priority.
docker exec "${DB_CONTAINER}" sh -c \
  "mysqldump -u ${DB_USER} -p'${DB_PASS}' --no-tablespaces ${DB_NAME}" \
  | nice -n 19 gzip > "${DB_DUMP}"
echo "      done: $(du -h "${DB_DUMP}" | cut -f1)"

############################################################################
# Step 2: Elasticsearch data (tarball)
############################################################################

if [ -n "${ES_DATA_DIR}" ] && [ -d "${ES_DATA_DIR}" ]; then
  ES_DUMP="${BACKUP_DIR}/es_${TS}.tar.gz"
  echo "[2/3] ES tarball -> ${ES_DUMP}"
  # ionice -c3: idle disk class, low-priority use of I/O
  nice -n 19 ionice -c3 tar -czf "${ES_DUMP}" -C "${ES_DATA_DIR}" .
  echo "      done: $(du -h "${ES_DUMP}" | cut -f1)"
else
  echo "[2/3] skipping ES (ES_DATA_DIR unset or missing)"
fi

############################################################################
# Step 3: rsync app dir + artifacts to remote
#
# Excludes:
#   backups/          ould recursively copy history
#   db/, mysql-data/  locked, root-owned, useless
#   log/, tmp/        junk
#   .git/             just git clone later
#   node_modules/     reproducible
#
# TRAILING SLASH ON THE SOURCE IS ESSENTIAL:
#   src/  -> copies CONTENTS of src into dest
#   src   -> creates dest/src (annoying double-nesting)
#
#  -a         archive mode (recursive and preserves perms/times/symlinks)
#  -z         compress in flight (code + sql are text so it compresses well)
#  --bwlimit  caps throughput so the link stays usable
############################################################################

echo "[3/3] rsync ${APP_DIR} -> ${REMOTE}:${REMOTE_DIR}"
ssh "${REMOTE}" "mkdir -p '${REMOTE_DIR}/fanfiction-lol' '${REMOTE_DIR}/artifacts'"

nice -n 19 ionice -c3 rsync -az --bwlimit="${BW_LIMIT}" \
  --exclude='backups/' \
  --exclude='log/' \
  --exclude='tmp/' \
  --exclude='.git/' \
  --exclude='node_modules/' \
  --exclude='db/' \
  --exclude='mysql-data/' \
  "${APP_DIR}/" "${REMOTE}:${REMOTE_DIR}/fanfiction-lol/"

# Push just today's dump artifacts
nice -n 19 ionice -c3 rsync -az --bwlimit="${BW_LIMIT}" \
  "${DB_DUMP}" \
  $([ -n "${ES_DATA_DIR}" ] && echo "${ES_DUMP:-}") \
  "${REMOTE}:${REMOTE_DIR}/artifacts/"

############################################################################
# Manifest + retention
############################################################################

ssh "${REMOTE}" "cat > '${REMOTE_DIR}/backup_info.txt'" <<EOF
BACKUP .NFO
===========
Date:        ${TS} ($(date))
Source host: $(hostname)
App dir:     ${APP_DIR}
Contents:    full app dir (code, config, storage, es/) + artifacts/
Restore:     provision containers, import artifacts/db_${TS}.sql.gz into
             mariadb, restore config/local.yml + storage/, rebuild index.
EOF

# Drop artifacts older than RETENTION_DAYS on SERVER machine
find "${BACKUP_DIR}" -name 'db_*.sql.gz' -mtime "+${RETENTION_DAYS}" -delete
find "${BACKUP_DIR}" -name 'es_*.tar.gz' -mtime "+${RETENTION_DAYS}" -delete

echo "=== done -> ${REMOTE}:${REMOTE_DIR} ==="