#!/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"

# Network and mount configuration
REMOTE_IP="172.16.1.0"
REMOTE_USER=""
RESTIC_REPOSITORY="sftp:${REMOTE_USER}@${REMOTE_IP}:${RESTIC_REPOSITORY})"

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"
}

# Cleanup function (runs on exit)
cleanup() {
	# 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
}

# Set trap to ensure cleanup runs on exit
trap cleanup EXIT

log "Starting backup process..."
BACKUP_STATUS="failed"  # Default to failed, will change on success

# Check if NAS is reachable
log "Checking if $REMOTE_IP is reachable..."
if ! ping -c 3 -W 5 "$REMOTE_IP" > /dev/null 2>&1; then
    log "ERROR: Cannot reach $REMOTE_IP - backup aborted"
    exit 1
fi
log "$REMOTE_IP is reachable"

# Test SSH connection
log "Testing SSH connection to $REMOTE_USER@$REMOTE_IP..."
if ! ssh -o ConnectTimeout=10 -o BatchMode=yes "$REMOTE_USER@$REMOTE_IP" "exit" 2>> "$LOG_FILE"; then
    log "ERROR: Cannot establish SSH connection to $REMOTE_USER@$REMOTE_IP"
    log "Make sure SSH key authentication is set up"
    exit 1
fi
log "SSH connection successful"


# Check if repository exists, if not try to initialize
log "Checking repository..."
if ! restic -r "$RESTIC_REPOSITORY" snapshots > /dev/null 2>&1; then
    log "Repository not found or not initialized"
    exit 1
fi

log "Starting restic 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
    log "Pruning old backups..."
    restic -r "$RESTIC_REPOSITORY" forget \
        --keep-daily 7 \
        --keep-weekly 4 \
        --keep-monthly 6 \
        --prune \
        >> "$LOG_FILE" 2>&1
    
    if [ $? -eq 0 ]; then
        log "Prune completed successfully"
        BACKUP_STATUS="success"
    else
        log "Warning: Prune had issues but backup succeeded"
        BACKUP_STATUS="success"
    fi
else
    log "ERROR: Backup failed!"
    BACKUP_STATUS="failed"
    exit 1
fi

exit 0
