#!/bin/bash
#
# Full server backup for Final Target: one encrypted file that restores the
# whole install, not just the data.
#
# The nightly database backup (ft-backup.sh) covers content only. Restoring it
# on a bare server gives you rows and no site: no code, no .env, no uploaded
# media, no Apache or systemd configuration. This covers all of it.
#
# Contents of the archive:
#   database.sql.gz          the PostgreSQL dump
#   code/                    the application, without venv or caches
#   env/.env                 the live environment file
#   media/                   uploads: logos, thumbnails, HLS output
#   config/                  Apache vhost, systemd unit, crontab, versions
#   RESTORE.txt              the steps, written into the archive itself
#
# WARNING. This archive contains .env, which holds every credential the site
# uses. It is written mode 600 and encrypted, and it should be treated like the
# passphrase itself. Never put it anywhere that syncs to a cloud drive.
#
# Runs weekly. Two copies are kept, the newest and the one before it, and the
# older is only removed after the new one has been verified. One overwritten
# copy would be lost the first time a fault went unnoticed for a week.
#
# Install:
#   chmod 700 /root/ft-full-backup.sh
#   # uses the same passphrase file as the database backup
#   0 2 * * 0 /root/ft-full-backup.sh >> /var/log/ft-full-backup.log 2>&1
#
set -euo pipefail

DB_NAME="finaltarget_db"
APP_DIR="/home/finaltarget/public_html/backend"
MEDIA_DIR="${APP_DIR}/media"
BACKUP_DIR="/root/backups/full"
PASS_FILE="/root/.backup-pass"
KEEP_COPIES=2

STAMP=$(date +%F-%H%M)
TARGET="${BACKUP_DIR}/ft-full-${STAMP}.tar.gz.enc"
WORK=$(mktemp -d /tmp/ftfull.XXXXXX)

cleanup() { rm -rf "$WORK"; }
trap cleanup EXIT

if [ ! -f "$PASS_FILE" ]; then
    echo "$(date '+%F %T') ERROR: $PASS_FILE is missing. Refusing to write an unencrypted backup."
    exit 1
fi

mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR" "$(dirname "$BACKUP_DIR")"
cd /tmp

echo "$(date '+%F %T') Starting full backup"

# ── 1. Database ──────────────────────────────────────────────────────────────
sudo -u postgres pg_dump "$DB_NAME" | gzip -9 > "${WORK}/database.sql.gz"
echo "  database: $(du -h "${WORK}/database.sql.gz" | cut -f1)"

# ── 2. Code, without the parts that are rebuilt rather than restored ─────────
mkdir -p "${WORK}/code"
# Anchored to ./ so only the top level directories are skipped. A bare
# --exclude='media' also matches apps/media, and the backup would quietly be
# missing an app.
tar cf - -C "$APP_DIR" \
    --exclude='./venv' \
    --exclude='__pycache__' \
    --exclude='*.pyc' \
    --exclude='./node_modules' \
    --exclude='./media' \
    --exclude='./staticfiles' \
    --exclude='./.env' \
    . | tar xf - -C "${WORK}/code"
echo "  code: $(du -sh "${WORK}/code" | cut -f1)"

# ── 3. The environment file, kept apart so it is obvious what it is ──────────
mkdir -p "${WORK}/env"
if [ -f "${APP_DIR}/.env" ]; then
    cp "${APP_DIR}/.env" "${WORK}/env/.env"
    chmod 600 "${WORK}/env/.env"
fi

# ── 4. Media. The one thing that cannot be regenerated from anywhere ─────────
mkdir -p "${WORK}/media"
if [ -d "$MEDIA_DIR" ]; then
    tar cf - -C "$MEDIA_DIR" . | tar xf - -C "${WORK}/media"
    echo "  media: $(du -sh "${WORK}/media" | cut -f1)"
fi

# ── 5. Server configuration ──────────────────────────────────────────────────
mkdir -p "${WORK}/config"
cp /etc/systemd/system/finaltarget.service "${WORK}/config/" 2>/dev/null || true
cp /etc/apache2/conf.d/pre_virtualhost_global.conf "${WORK}/config/" 2>/dev/null || true
cp /usr/local/apache/conf/httpd.conf "${WORK}/config/httpd.conf" 2>/dev/null || true
crontab -l > "${WORK}/config/root.crontab" 2>/dev/null || true
rpm -qa --qf '%{NAME}-%{VERSION}\n' 2>/dev/null | sort > "${WORK}/config/packages.txt" || true
"${APP_DIR}/venv/bin/pip" freeze > "${WORK}/config/requirements.frozen.txt" 2>/dev/null || true
{
    echo "Taken:      $(date '+%F %T %Z')"
    echo "Host:       $(hostname)"
    echo "OS:         $(cat /etc/redhat-release 2>/dev/null || uname -a)"
    echo "Python:     $("${APP_DIR}/venv/bin/python" -V 2>&1 || true)"
    echo "PostgreSQL: $(sudo -u postgres psql -tAc 'select version()' 2>/dev/null | head -1 || true)"
} > "${WORK}/config/manifest.txt"

# ── 6. The restore steps, inside the archive ─────────────────────────────────
cat > "${WORK}/RESTORE.txt" <<'RESTORE'
Restoring Final Target from this archive
========================================

You need this file and the backup passphrase. Without the passphrase nothing
here can be read, by you or by anyone else.

1. Decrypt and unpack

   openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 \
       -pass file:/root/.backup-pass \
       -in ft-full-YYYY-MM-DD-HHMM.tar.gz.enc \
     | tar xzf - -C /root/restore

2. Prepare the server
   Install Python 3.13, PostgreSQL, Apache. config/packages.txt lists what was
   installed on the original machine, config/manifest.txt records the versions.

3. Put the code and the environment back

   mkdir -p /home/finaltarget/public_html/backend
   cp -a /root/restore/code/. /home/finaltarget/public_html/backend/
   cp /root/restore/env/.env  /home/finaltarget/public_html/backend/.env
   chmod 600 /home/finaltarget/public_html/backend/.env

4. Rebuild the virtual environment. It is deliberately not in the archive,
   because compiled packages do not move between machines.

   cd /home/finaltarget/public_html/backend
   python3 -m venv venv
   venv/bin/pip install -r config/requirements.frozen.txt

5. Restore the database

   sudo -u postgres createdb finaltarget_db
   gunzip -c /root/restore/database.sql.gz | sudo -u postgres psql finaltarget_db

6. Restore the media

   cp -a /root/restore/media/. /home/finaltarget/public_html/backend/media/

7. Restore the service and the schedule

   cp /root/restore/config/finaltarget.service /etc/systemd/system/
   systemctl daemon-reload && systemctl enable --now finaltarget
   crontab /root/restore/config/root.crontab

8. Check before pointing DNS at it

   venv/bin/python manage.py migrate --plan --settings=config.settings.production
   curl -I http://127.0.0.1:8001/

Note. FIELD_ENCRYPTION_KEY inside .env is what makes the encrypted database
columns readable. If it is ever regenerated, the old values are lost for good.
RESTORE

# ── 7. Seal it ───────────────────────────────────────────────────────────────
tar czf - -C "$WORK" . \
  | openssl enc -aes-256-cbc -pbkdf2 -iter 200000 -salt \
        -pass "file:${PASS_FILE}" \
        -out "$TARGET"
chmod 600 "$TARGET"

SIZE=$(du -h "$TARGET" | cut -f1)
echo "$(date '+%F %T') Written: $TARGET ($SIZE)"

# ── 8. Verify. An archive nobody can open is not a backup ────────────────────
if openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 \
       -pass "file:${PASS_FILE}" -in "$TARGET" 2>/dev/null \
     | tar tzf - > "${WORK}/listing.txt" 2>/dev/null; then
    COUNT=$(wc -l < "${WORK}/listing.txt")
    for required in ./database.sql.gz ./RESTORE.txt ./env/.env; do
        if ! grep -qx -- "$required" "${WORK}/listing.txt"; then
            echo "$(date '+%F %T') ERROR: $required missing from the archive."
            exit 1
        fi
    done
    echo "$(date '+%F %T') Verified: decrypts, unpacks, $COUNT entries, all expected parts present."
else
    echo "$(date '+%F %T') ERROR: $TARGET failed verification. Investigate before trusting it."
    exit 1
fi

# ── 9. Retention: keep the newest KEEP_COPIES, delete the rest ───────────────
# Reached only when verification passed above, so the previous good archive is
# never removed on the strength of a broken new one.
ls -1t "${BACKUP_DIR}"/ft-full-*.tar.gz.enc 2>/dev/null \
  | tail -n +$((KEEP_COPIES + 1)) \
  | while read -r old; do
        echo "$(date '+%F %T') Removing superseded backup: $old"
        rm -f -- "$old"
    done

echo "$(date '+%F %T') Done. Held: $(ls -1 "$BACKUP_DIR" | wc -l) archive(s), $(du -sh "$BACKUP_DIR" | cut -f1) total."
