#!/bin/bash

# Configuration
RESTIC_REPOSITORY="/mnt/truenas/backups/restic/<servername>"
RESTIC_PASSWORD_FILE="/root/.restic-password"
BACKUP_SOURCE="/home/aaron"
EXCLUDE_FILE="/root/.restic-exclude"
LOG_DIR="/var/log/restic"
LOG_FILE="$LOG_DIR/home-backup-$(date '+%Y%m%d-%H%M%S').log"

GOTIFY_TOKEN="<token>"
GOTIFY_IP="172.16.0.7"

# Export password
export RESTIC_PASSWORD_FILE

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "Starting backup..."

# Run backup
restic -r "$RESTIC_REPOSITORY" backup "$BACKUP_SOURCE" \
    --exclude-file="$EXCLUDE_FILE" \
    --verbose \
    >> "$LOG_FILE" 2>&1

if [ $? -eq 0 ]; then
    log "Backup completed successfully"
    
    # Cleanup old snapshots (keep last 7 daily, 4 weekly, 6 monthly)
    log "Pruning old backups..."
    restic -r "$RESTIC_REPOSITORY" forget \
        --keep-daily 7 \
        --keep-weekly 4 \
        --keep-monthly 6 \
        --prune \
        >> "$LOG_FILE" 2>&1
    
    log "Prune completed"
    BACKUP_STATUS="success"
else
    log "Backup failed!"
    BACKUP_STATUS="failed"
fi

# Gotify Notification
TITLE="$(hostname) restic backup - $BACKUP_STATUS"
PRIORITY=0
GOTIFY_URL="http://$GOTIFY_IP:8081/message?token=$GOTIFY_TOKEN"
LOG_CONTENT=$(cat "$LOG_FILE")

curl -s -S --data-urlencode "title=$TITLE" --data-urlencode "message=$LOG_CONTENT" "$GOTIFY_URL"

# Optional: Clean up old log files (keep last 30 days)
find "$LOG_DIR" -name "backup-*.log" -mtime +30 -delete

# Exit with appropriate code
[ "$BACKUP_STATUS" = "success" ] && exit 0 || exit 1
