#!/usr/bin/env bash
#
# Mirror a local backup folder to Google Drive with rclone in Docker.
# Call it at the end of your nightly backup script, after the local backup is done.
#
# A failed sync is not an error right away: the local backup is already safe and
# the next run catches up. This script exits 1 (so your systemd unit fails and
# OnFailure= can alert you) only after GRACE_DAYS days without a successful sync.
# If it has never succeeded, the first failure counts as overdue.
#
# Usage:
#   BACKUP_DIR=/path/to/backups ./drive-sync.sh
#
# Upload only encrypted files: Drive becomes an exact copy of BACKUP_DIR.
# From: https://jamongx.com/rclone-google-drive-backup-docker/
set -euo pipefail

BACKUP_DIR=${BACKUP_DIR:?set BACKUP_DIR to the folder to mirror}
RCLONE_CONFIG_DIR=${RCLONE_CONFIG_DIR:-$HOME/.config/rclone}   # written by gdrive-auth.sh
RCLONE_IMAGE=${RCLONE_IMAGE:-rclone/rclone:1.76.0}
DRIVE_REMOTE=${DRIVE_REMOTE:-gdrive:}     # rclone's root is the folder pinned with root_folder_id
GRACE_DAYS=${GRACE_DAYS:-3}
STATE_FILE=${STATE_FILE:-$HOME/.local/state/drive-sync.last}

mkdir -p "$(dirname "$STATE_FILE")"

if docker run --rm --user "$(id -u):$(id -g)" \
     -v "$RCLONE_CONFIG_DIR":/config/rclone \
     -v "$BACKUP_DIR":/src:ro \
     "$RCLONE_IMAGE" sync /src "$DRIVE_REMOTE" --log-level ERROR; then
  date +%s > "$STATE_FILE"
  echo "drive-sync: done"
  exit 0
fi

last=$(cat "$STATE_FILE" 2>/dev/null || echo 0)
behind_days=$(( ( $(date +%s) - last ) / 86400 ))
if (( behind_days >= GRACE_DAYS )); then
  echo "drive-sync: no successful sync for ${behind_days} days" >&2
  exit 1
fi
echo "drive-sync: failed (${behind_days} day(s) since the last success, within the ${GRACE_DAYS}-day grace)" >&2
