#!/bin/sh
# A backup a day, kept for two weeks. 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.
#
# Reads the service's environment file for where everything is, which is why
# it runs as root, and why the backups are readable by root alone: the
# archive holds the SIP passwords and that file.
set -eu

env_file=/etc/nuxpbx/nuxpbx.env
backups=/var/lib/nuxpbx/backups
keep=14

# 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"

mkdir -p "$backups"
chmod 700 "$backups"
nuxpbx backup "$backups/nuxpbx-$(date -u +%Y%m%d-%H%M%S).tar.gz" >/dev/null

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