#!/bin/sh
# A backup a day, kept for two weeks, and sent wherever the machine says.
# Runs as root from cron.daily on Debian and periodic/daily on Alpine, so
# nobody has to remember it: a phone system whose only copy is the disk it
# runs on is one bad disk from a reinstall, and a backup on that same disk
# goes with it.
#
# Reads the service's environment file for where everything is, which is why
# it runs as root. The archives belong to the service afterwards: they hold
# the SIP passwords and that file, which is what the service already holds,
# and it is the service that sends one again from the screen.
set -eu

# The one the service reads. Overridable so the check can run this file
# itself rather than a copy of it that could drift away from it.
env_file=${NUXPBX_ENV_FILE:-/etc/nuxpbx/nuxpbx.env}

# Not set up yet: nothing to keep, and nuxpbx backup would only complain.
[ -s "$env_file" ] || exit 0

# Line by line, the way systemd reads it, not sourced: NUXPBX_DB is a
# connection string with spaces in it and no quotes around it, and `.` would
# turn "host=x port=y" into five assignments of which only the first is ours.
while IFS= read -r line; do
	case "$line" in '' | '#'*) continue ;; esac
	export "$line"
done <"$env_file"
export NUXPBX_ENV_FILE="$env_file"

backups=${NUXPBX_BACKUPS:-/var/lib/nuxpbx/backups}
keep=${NUXPBX_BACKUP_KEEP:-14}
# Anything but a number is a typo, and a typo here would read as "keep none"
# in the arithmetic below and empty the directory this whole file exists to
# fill. Zero means keep every one, the same as it does at the destination.
case "$keep" in
'' | *[!0-9]*) keep=14 ;;
esac

mkdir -p "$backups"
chmod 700 "$backups"

# --send every night, whether or not a destination is set: with none set it
# says so and the backup is still written. A send that fails leaves the
# archive here and exits non-zero, which cron mails on, so the tidying below
# still runs and the status is passed on at the end.
status=0
nuxpbx backup --send "$backups/nuxpbx-$(date -u +%Y%m%d-%H%M%S).tar.gz" >/dev/null || status=$?

# The names sort by date, so the oldest are the ones past the count.
if [ "$keep" -gt 0 ]; then
	find "$backups" -name 'nuxpbx-*.tar.gz' | sort -r | tail -n +"$((keep + 1))" | while read -r old; do
		rm -f "$old"
	done
fi

# To the service, so the interface can send one again without being root.
if id -u nuxpbx >/dev/null 2>&1; then
	chown -R nuxpbx:nuxpbx "$backups"
fi

exit "$status"
