#!/bin/bash
# Wombat-Email: send the backups to cloud storage, through rclone (installed by installer/90-backup.sh).
#   wombat-email-backup-link drive|dropbox|onedrive|box     links the account, proves it, switches over
#   wombat-email-backup-link other                          rclone's own questions (S3, SFTP, anything it knows)
#   ... --existing                                          only links, for wombat-email-restore on a new server
# The approval happens in the browser on your computer: rclone waits on 127.0.0.1:53682 here, which the
# ssh -L command the panel gives carries to it. The account's token stays in root's rclone.conf (600). What's
# stored is encrypted with the backup password first, so the storage only ever holds scrambled data.
# Nothing changes until a repository there has been made and read back; if this fails, backups stay where they are.
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
REMOTE=wombat-backup
service=${1:-}; existing=0; [ "${2:-}" = --existing ] && existing=1
case $service in
    drive) type=drive; name="Google Drive" ;;
    dropbox) type=dropbox; name=Dropbox ;;
    onedrive) type=onedrive; name=OneDrive ;;
    box) type=box; name=Box ;;
    other) type=; name="your storage" ;;
    *) sed -n '2,5p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
fail() { echo; echo "That didn't work: $*"; echo "Backups are still going where they were. Run this again to retry."; exit 1; }

install -d -m 700 /root/.config /root/.config/rclone
touch "$RCLONE_CONFIG"; chmod 600 "$RCLONE_CONFIG"
rclone config delete "$REMOTE" >/dev/null 2>&1
if [ -z "$type" ]; then
    echo "This only works in a window opened with the panel's ssh -L command: your browser's Allow comes back"
    echo "through it. If you logged in some other way, press Ctrl+C, log in with that command, and run this again."
    echo
    echo "rclone asks its questions now. When it asks for a name, type: $REMOTE"
    rclone config
    rclone listremotes | grep -qx "$REMOTE:" || fail "there's no remote called $REMOTE"
    t=$(rclone config show "$REMOTE" | sed -n 's/^type = //p' | head -1)
    case $t in   # the name the panel shows; a Dropbox made this way is the owner's own app folder
        dropbox) name="Dropbox (your app folder)" ;; drive) name="Google Drive" ;; onedrive) name=OneDrive ;; box) name=Box ;;
        s3) name="S3 storage" ;; sftp) name="SFTP storage" ;; *) name="$t storage" ;;
    esac
else
    { printf '[%s]\ntype = %s\n' "$REMOTE" "$type"
      # Google: only the files rclone itself makes, not the rest of the Drive.
      [ "$type" = drive ] && echo 'scope = drive.file'; } >> "$RCLONE_CONFIG"
    echo
    echo "Next comes a link starting with http://127.0.0.1:53682/auth."
    echo "Open it in your browser, sign in to $name if asked, and press Allow. Then come back: this carries on by itself."
    echo "It only works in a window opened with the ssh -L command on the panel's page."
    echo
    timeout 600 rclone config reconnect "$REMOTE:" --auto-confirm \
        || { rclone config delete "$REMOTE"; fail "$name didn't link. Check this window was opened with the ssh -L command."; }
fi
rclone lsf "$REMOTE:" --max-depth 1 >/dev/null || fail "linked, but $name can't be read"
echo "Linked to $name."
printf '%s\n' "$name" > /var/lib/wombat-email/backup-where.new; chmod 644 /var/lib/wombat-email/backup-where.new
if [ "$existing" = 1 ]; then mv /var/lib/wombat-email/backup-where.new /var/lib/wombat-email/backup-where; echo "Now run: wombat-email-restore"; exit 0; fi

export RESTIC_REPOSITORY=rclone:$REMOTE:wombat-email-$HOSTNAME RESTIC_PASSWORD_FILE=/etc/wombat-email/secrets/backup-password
echo "Making the backup storage there. This can take several minutes, even with very little mail..."
if ! restic cat config >/dev/null 2>&1; then
    restic init >/dev/null 2>&1 || fail "the backup storage couldn't be made in $name"
fi
restic cat config >/dev/null 2>&1 || fail "the backup storage in $name can't be read back with this server's backup password"

sed -i "s|^BACKUP_REPO=.*|BACKUP_REPO=$RESTIC_REPOSITORY|" /etc/wombat-email/settings
mv /var/lib/wombat-email/backup-where.new /var/lib/wombat-email/backup-where
touch /var/lib/wombat-email/requests/sync; chown wombat-panel /var/lib/wombat-email/requests/sync
systemctl start --no-block wombat-email-backup.service
echo
echo "Backups now go to $name. The first one has started and keeps going if you close this window."
echo "It can take a while with a lot of mail; the panel's Settings page shows how it's going."
echo "The old backups stay in /var/backups/wombat-email/restic until you delete them."
