#!/bin/bash
# Daily email backup — downloads new emails via IMAP to atlantis NFS mount
#
# Writes directly to /mnt/atlantis_archive/old_emails/ (NFS mount to atlantis:/volume1/archive)
# Also keeps a local copy at /tmp/gmail_backup for quick access
# Incremental — skips already-downloaded .eml files
# Never deletes — emails removed from source stay in backup
#
# Proton Bridge must be running for admin@thevish.io backup.
# If bridge is down, Gmail accounts still back up fine (script continues on error).
#
# Cron: 0 3 * * * /home/homelab/organized/repos/homelab/scripts/gmail-backup-daily.sh

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ATLANTIS_BACKUP="/mnt/atlantis_archive/old_emails"
LOCAL_BACKUP="/tmp/gmail_backup"
LOG="/tmp/gmail-backup-daily.log"

echo "$(date '+%Y-%m-%d %H:%M:%S') — Starting email backup" >> "$LOG"

# Check NFS mount
if ! mountpoint -q /mnt/atlantis_archive; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') — WARNING: /mnt/atlantis_archive not mounted, trying to mount..." >> "$LOG"
    sudo mount /mnt/atlantis_archive >> "$LOG" 2>&1
    if ! mountpoint -q /mnt/atlantis_archive; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') — ERROR: Cannot mount atlantis_archive, falling back to local only" >> "$LOG"
        ATLANTIS_BACKUP=""
    fi
fi

# Download to atlantis (primary destination)
if [ -n "$ATLANTIS_BACKUP" ]; then
    python3 "$SCRIPT_DIR/gmail-backup.py" "$ATLANTIS_BACKUP" >> "$LOG" 2>&1 || true
    TOTAL=$(find "$ATLANTIS_BACKUP" -name "*.eml" 2>/dev/null | wc -l)
    echo "$(date '+%Y-%m-%d %H:%M:%S') — Atlantis backup: $TOTAL total emails" >> "$LOG"
fi

# Also keep a local copy (fast access, survives NFS outage)
python3 "$SCRIPT_DIR/gmail-backup.py" "$LOCAL_BACKUP" >> "$LOG" 2>&1 || true
LOCAL_TOTAL=$(find "$LOCAL_BACKUP" -name "*.eml" 2>/dev/null | wc -l)
echo "$(date '+%Y-%m-%d %H:%M:%S') — Local backup: $LOCAL_TOTAL total emails" >> "$LOG"

echo "$(date '+%Y-%m-%d %H:%M:%S') — Done" >> "$LOG"
