#!/bin/bash
#
# Purpose : Back up your home folder with restic to your Nextcloud files, in
#           .backup-<this Mac's name>. `configure backup` sets it up.
#
# launchd starts the Federated Backup app hourly and at login, and the app
# runs this. It backs up once a day, so a Mac that was asleep or off catches
# up soon after. The app exists so that you can give it Full Disk Access:
# what it runs gets that access too, and without it macOS keeps restic out of
# Desktop, Documents, Mail and the like.
#
# Keeps 7 daily, 4 weekly and 6 monthly backups. To leave out more, list
# paths or patterns in ~/Library/Application Support/Federated Connector/
# backup-exclude, one per line.

# Wrapped in { ...; exit; } so bash reads the whole script up front; an update
# may replace this file while a backup is running.
{

CONNECTOR="$(cd "$(dirname "$0")/.." && pwd)"
CONF_DIR="$HOME/Library/Application Support/Federated Connector"
USER_EXCLUDE="$CONF_DIR/backup-exclude"
STAMP="$CONF_DIR/backup-last"
NOW_REQUEST="$CONF_DIR/backup-now"
ACCESS_CHECK="$CONF_DIR/backup-access-check"
LOCK="$CONF_DIR/backup.lock"
LOG_DIR="$HOME/Library/Logs/Federated Connector"
LOG="$LOG_DIR/backup.log"
DAY=82800  # 23 hours, so the daily backup doesn't drift later each day

# Full Disk Access is what lets this read the TCC folder
full_disk_access() {
  ls "$HOME/Library/Application Support/com.apple.TCC" > /dev/null 2>&1
}

# configure asks, by starting the app, whether it has Full Disk Access
if [ -f "$ACCESS_CHECK" ]; then
  if full_disk_access; then echo yes > "$ACCESS_CHECK"; else echo no > "$ACCESS_CHECK"; fi
  exit 0
fi

mkdir -p "$LOG_DIR"
if [ "$(stat -f %z "$LOG" 2> /dev/null || echo 0)" -gt 5000000 ]; then
  mv -f "$LOG" "$LOG.1"
fi
exec >> "$LOG" 2>&1

# Tell you when a backup fails, as no one watches launchd
notify() {
  osascript -e 'on run argv' -e 'display notification (item 2 of argv) with title (item 1 of argv)' \
    -e 'end run' "$1" "$2" 2> /dev/null
}

fail() {
  echo "$(date '+%F %T') Backup failed: $1"
  notify "Backup failed" "$1"
  rm -f "$LOCK"
  exit 1
}

# Once a day, unless configure asked for one now
if [ -f "$NOW_REQUEST" ]; then
  rm -f "$NOW_REQUEST"
elif [ -f "$STAMP" ] && [ $(($(date +%s) - $(stat -f %m "$STAMP"))) -lt $DAY ]; then
  exit 0
fi

# One backup at a time
if [ -f "$LOCK" ] && kill -0 "$(cat "$LOCK" 2> /dev/null)" 2> /dev/null; then
  exit 0
fi
echo $$ > "$LOCK"

source "$CONNECTOR/system/backup-env.sh" || fail "Backups aren't set up. Run: configure backup"
[ -n "$RESTIC_REPOSITORY" ] || fail "Backups aren't set up. Run: configure backup"
[ -n "$RESTIC_PASSWORD_COMMAND" ] || fail "The backup's passphrase isn't in your keychain. Run: configure backup"
if ! command -v restic > /dev/null || ! command -v rclone > /dev/null; then
  fail "restic or rclone is missing. Run: configure backup"
fi

if ! full_disk_access; then
  notify "Backup can't read all your files" \
    "Give Federated Backup Full Disk Access (run: configure backup). Backing up what it can."
fi

# Run at login, perhaps before the network is up; give it a few minutes
for _ in 1 2 3 4 5 6 7 8 9 10; do
  curl -sf --max-time 10 -o /dev/null "${BACKUP_WEBDAV%%/remote.php/*}/status.php" && break
  sleep 30
done

L="$HOME/Library"
# Rebuilt by restic, or by reinstalling, so not worth the space
excludes=(
  "$HOME/.Trash"
  "$L/Caches"
  "$L/Logs"
  "$L/Containers/*/Data/Library/Caches"
  "$L/Group Containers/*/Library/Caches"
  "$L/Developer/Xcode/DerivedData"
  "$L/Developer/Xcode/iOS DeviceSupport"
  "$L/Developer/CoreSimulator"
  # Files already in the cloud. Reading them would also download the ones
  # macOS keeps only in the cloud.
  "$HOME/Nextcloud"
  "$L/CloudStorage"
  "$L/Mobile Documents"
  # Docker's and other VMs' disks: large, and changing whenever they run
  "$L/Containers/com.docker.docker"
  "$HOME/.orbstack"
  "$HOME/.colima"
  "$HOME/.lima"
  "$L/Containers/com.utmapp.UTM"
  # Package caches and tool installs
  "$HOME/.local/share/federated-connector"
  "$HOME/.npm"
  "$HOME/.bun/install/cache"
  "$HOME/.cargo/registry"
  "$HOME/.cargo/git"
  "$HOME/go/pkg"
  "$HOME/.local/share/mise/installs"
  "$HOME/.local/share/mise/downloads"
  "$HOME/.local/share/uv"
  "$HOME/.local/share/claude"
  "$HOME/.opencode/bin"
  # The agents' own installs and downloads; their settings, memories and
  # sessions are kept
  "$HOME/.hermes/hermes-agent"
  "$HOME/.hermes/tools"
  "$HOME/.hermes/installs"
  "$HOME/.hermes/bin"
  "$HOME/.hermes/cache"
  # Models can be downloaded again
  "$HOME/.ollama/models"
  "$HOME/.lmstudio/models"
  "$HOME/.cache"
  # Electron and Chromium apps (Element, browsers, editors) keep caches here
  "$L/Application Support/*/Cache"
  "$L/Application Support/**/Code Cache"
  "$L/Application Support/**/GPUCache"
  "$L/Application Support/**/Service Worker/CacheStorage"
  # Element's search index for encrypted messages, which it rebuilds
  "$L/Application Support/Element/EventStore"
)
# Without Full Disk Access, reading these makes macOS ask you, and restic
# waits for the answer, which no one gives at night; the rest that Full Disk
# Access guards (Mail, Messages, Safari...) is just refused
if ! full_disk_access; then
  excludes+=(
    "$HOME/Desktop"
    "$HOME/Documents"
    "$HOME/Downloads"
    "$L/Containers"
    "$L/Group Containers"
    # Photos asks too
    "$L/Photos"
    "$HOME/Pictures/*.photoslibrary"
  )
fi
exclude_args=(--exclude-caches)
for path in "${excludes[@]}"; do
  exclude_args+=(--exclude "$path")
done
[ -f "$USER_EXCLUDE" ] && exclude_args+=(--exclude-file "$USER_EXCLUDE")

echo "$(date '+%F %T') Backing up $HOME to $BACKUP_DIR in your Nextcloud files..."
restic backup --one-file-system --host "$BACKUP_HOST" "${exclude_args[@]}" "$HOME"
status=$?
# 3 means some files couldn't be read; the rest were backed up
[ $status -eq 0 ] || [ $status -eq 3 ] || fail "restic couldn't back up $HOME (exit $status). See $LOG"

echo "$(date '+%F %T') Removing old backups..."
restic forget --host "$BACKUP_HOST" --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune \
  || fail "restic couldn't remove old backups. See $LOG"

touch "$STAMP"
rm -f "$LOCK"
echo "$(date '+%F %T') Backup finished."
exit 0
}
