#!/bin/bash
# Wombat-Email: bring a server back from its backup (installed by installer/90-backup.sh).
# On a new server: run the installer with the same hostname, then
#   wombat-email-backup-link drive --existing     (or dropbox, onedrive, box, other: links the storage)
#   wombat-email-restore                          the newest backup of this hostname
#   wombat-email-restore --repo REPO              any restic repository instead
# It asks for the backup password (the one you saved), and for the hostname to be typed: it replaces this
# server's settings, databases and mail with the backup's. Then the installer puts everything in line.
set -uo pipefail
[ "$(id -u)" = 0 ] || { echo "Run it as root."; exit 1; }
. /etc/wombat-email/settings
export RCLONE_CONFIG=/root/.config/rclone/rclone.conf RCLONE_FAST_LIST=true   # far fewer requests to cloud storage
export RESTIC_REPOSITORY=rclone:wombat-backup:wombat-email-$HOSTNAME
[ "${1:-}" = --repo ] && [ -n "${2:-}" ] && RESTIC_REPOSITORY=$2
DUMP=/var/backups/wombat-email/dumps
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
export RESTIC_PASSWORD_FILE=$tmp/password

read -rsp "Your backup password: " p </dev/tty; echo
(umask 077; printf '%s' "$p" > "$RESTIC_PASSWORD_FILE"); unset p
latest=$(restic snapshots --json --latest 1 2>/dev/null | python3 -I -c 'import json,sys
s = json.load(sys.stdin) or []
print(s[-1]["time"][:16].replace("T", " "), s[-1]["short_id"], s[-1]["hostname"]) if s else None') \
    || { echo "Couldn't open the backups at $RESTIC_REPOSITORY. Check the password and that the storage is linked."; exit 1; }
[ -n "$latest" ] || { echo "There are no backups at $RESTIC_REPOSITORY."; exit 1; }
read -r when clock id from <<<"$latest"

boxes=$(runuser -u postgres -- psql -X -q -At -d wombat_email -c 'SELECT count(*) FROM mailboxes')
echo
echo "The newest backup: $when $clock, from $from."
echo "This REPLACES everything on $HOSTNAME with it: settings, passwords, databases and mail."
echo "This server has $boxes mailbox(es) now. Anything newer than the backup is lost from the database."
read -rp "To go ahead, type $HOSTNAME: " typed </dev/tty
[ "$typed" = "$HOSTNAME" ] || { echo "Stopped; nothing changed."; exit 1; }

started=$(date +%s)
services=(postfix dovecot rspamd apache2 php8.5-fpm)
echo "Stopping the mail and web services..."
systemctl stop "${services[@]}"
echo "Restoring (with a lot of mail, this takes a while)..."
rm -rf /etc/letsencrypt/accounts   # the backup's account owns its certificates; certbot can't choose between two
restic restore latest --target / --include /etc/wombat-email --include /etc/letsencrypt \
    --include /var/mail/vmail --include /var/lib/rspamd/dkim --include "$DUMP" \
    || { systemctl start "${services[@]}"; echo "The restore failed partway. Run this again."; exit 1; }
chown -R vmail:vmail /var/mail/vmail
chown -R _rspamd:_rspamd /var/lib/rspamd/dkim 2>/dev/null

echo "Restoring the databases..."
runuser -u postgres -- psql -X -q -d postgres < "$DUMP/pg-roles.sql" >/dev/null 2>&1   # most already exist; their passwords are what counts
runuser -u postgres -- pg_restore --clean --if-exists -d wombat_email < "$DUMP/wombat_email.dump"
runuser -u postgres -- pg_restore --clean --if-exists -d roundcube < "$DUMP/roundcube.dump"
if [ -s "$DUMP/redis.rdb" ]; then
    dir=$(redis-cli config get dir | tail -1); file=$(redis-cli config get dbfilename | tail -1)
    systemctl stop redis-server; install -o redis -g redis -m 660 "$DUMP/redis.rdb" "$dir/$file"; systemctl start redis-server
fi

systemctl start "${services[@]}"
echo "Putting everything in line..."
bash /opt/wombat-email/install.sh </dev/null
echo
echo "Done, in $(( ($(date +%s) - started) / 60 )) minutes. Sign in to the panel with your old password, and check your mail."
echo "If this server has a new address, the installer has updated the DNS; set its reverse DNS with your VPS host."
