who_need_help/scripts/install-production-backup-timer.sh

80 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
umask 077
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
config=${1:-"$ROOT/tmp/production-operations/backup.env"}
unit_dir=${SYSTEMD_USER_UNIT_DIR:-"$HOME/.config/systemd/user"}
if [[ "$config" != /* ]]; then
config="$ROOT/$config"
fi
if [[ ! -f "$config" || "$(stat -c '%a' "$config")" != 600 ]]; then
echo "The backup configuration must exist with mode 0600: $config" >&2
exit 2
fi
# shellcheck source=/dev/null
source "$config"
: "${BACKUP_ON_CALENDAR:?Set BACKUP_ON_CALENDAR}"
case "$BACKUP_ON_CALENDAR" in
*$'\n'* | *$'\r'*) echo "BACKUP_ON_CALENDAR must be one line." >&2; exit 2 ;;
esac
monitor_target=${MONITOR_SSH_TARGET:-buyvm-maya}
remote_monitor=${MONITOR_REMOTE_ROOT:-/home/simple/.local/lib/who-need-help}/production-external-monitor.py
remote_config=${MONITOR_REMOTE_CONFIG:-/home/simple/.config/who-need-help/monitor.json}
ssh_path=$(command -v ssh)
mkdir -p "$unit_dir"
chmod 700 "$HOME/.config" "$HOME/.config/systemd" "$unit_dir"
cat >"$unit_dir/who-need-help-production-backup.service" <<EOF
[Unit]
Description=Who Need Help encrypted off-server production backup and restore drill
Wants=network-online.target
After=network-online.target
OnFailure=who-need-help-production-backup-alert.service
[Service]
Type=oneshot
WorkingDirectory=$ROOT
ExecStart=$ROOT/scripts/production-offsite-backup.sh run $config
EOF
cat >"$unit_dir/who-need-help-production-backup-alert.service" <<EOF
[Unit]
Description=Notify operators that the Who Need Help production backup failed
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
ExecStart=$ssh_path -o BatchMode=yes $monitor_target /usr/bin/python3 $remote_monitor --config $remote_config notify-backup-failure --unit who-need-help-production-backup.service
EOF
cat >"$unit_dir/who-need-help-production-backup.timer" <<EOF
[Unit]
Description=Schedule Who Need Help encrypted production backups
[Timer]
OnCalendar=$BACKUP_ON_CALENDAR
Persistent=true
Unit=who-need-help-production-backup.service
[Install]
WantedBy=timers.target
EOF
chmod 600 \
"$unit_dir/who-need-help-production-backup.service" \
"$unit_dir/who-need-help-production-backup-alert.service" \
"$unit_dir/who-need-help-production-backup.timer"
systemctl --user daemon-reload
systemctl --user enable --now who-need-help-production-backup.timer
echo "Production backup timer installed without starting or changing the application."
systemctl --user list-timers --all --no-pager who-need-help-production-backup.timer