#!/bin/sh
# perlistream-backup — backups of the server's own state (not media).
#
#   sudo perlistream-backup create [--include-secrets] [--dest DIR] [--tag T]
#   sudo perlistream-backup list   [--dest DIR]
#   sudo perlistream-backup verify [FILE] [--deep]
#   sudo systemctl stop perlistream-server
#   sudo perlistream-backup restore FILE
#   sudo systemctl start perlistream-server
#
# Runs `python -m ops.backup` from the service root, as the service user, with
# the SAME environment as the service (PERLISTREAM_EDITION / PERLISTREAM_DATA_DIR
# from the unit + /etc/default/perlistream-server). Without that it would back
# up — or restore into — the wrong directory. Restore refuses to run while the
# server answers on its port: stop the service first.
set -eu

SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"
PREFIX="$(cd "$(dirname "$SELF")/.." && pwd)"
PY="$PREFIX/venv/bin/python"

if [ ! -x "$PY" ]; then
    echo "perlistream-backup: $PY missing — run: sudo $PREFIX/bin/setup-venv.sh" >&2
    exit 1
fi

export PERLISTREAM_EDITION=server
export PERLISTREAM_DATA_DIR=/var/lib/perlistream
export PERLISTREAM_PACKAGING=deb
if [ -f /etc/default/perlistream-server ]; then
    set -a
    # shellcheck disable=SC1091
    . /etc/default/perlistream-server
    set +a
fi

cd "$PREFIX/app"
if [ "$(id -u)" -eq 0 ] && id perlistream >/dev/null 2>&1; then
    if command -v runuser >/dev/null 2>&1; then
        exec runuser -u perlistream -- "$PY" -m ops.backup "$@"
    fi
    exec setpriv --reuid=perlistream --regid=perlistream --init-groups "$PY" -m ops.backup "$@"
fi
exec "$PY" -m ops.backup "$@"
