#!/bin/bash

# Configuration
SOURCE_REPO="/backup/restic/debian-4gb-nbg1-2"  
DEST_PATH="/mnt/truenas/backups/restic/debian-4gb-nbg1-2"
LOG_DIR="/var/log/restic-sync"
LOG_FILE="$LOG_DIR/sync-$(date '+%Y%m%d-%H%M%S').log"

# Network and mount configuration
REMOTE_IP="172.16.1.0"
MOUNT_POINT="/mnt/truenas/backups"
MOUNT_TIMEOUT=30

# Gotify configuration
GOTIFY_TOKEN="<token>"
GOTIFY_IP="172.16.0.7"

# Create log directory
mkdir -p "$LOG_DIR"

# Track if we mounted the share (so we know to unmount later)
WE_MOUNTED=false

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

# Cleanup function (runs on exit)
cleanup() {
    if [ "$WE_MOUNTED" = true ]; then
        log "Unmounting share..."
        umount "$MOUNT_POINT"
        if [ $? -eq 0 ]; then
            log "Share unmounted successfully"
        else
            log "Warning: Failed to unmount share"
        fi
    fi

		# Gotify Notification
		TITLE="Backup Sync - $SYNC_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
}								

trap cleanup EXIT

log "Starting backup repository sync..."
SYNC_STATUS="failed"

# Check if source exists
if [ ! -d "$SOURCE_REPO" ]; then
    log "ERROR: Source repository not found at $SOURCE_REPO"
    exit 1
fi

# 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 "NAS is reachable"

# Check if already mounted
if mountpoint -q "$MOUNT_POINT"; then
    log "Share already mounted"
else
    log "Mounting share..."
    if timeout "$MOUNT_TIMEOUT" mount "$MOUNT_POINT" >> "$LOG_FILE" 2>&1; then
        log "Share mounted successfully"
        WE_MOUNTED=true
        # Give it a moment to settle
        sleep 2
    else
        log "ERROR: Failed to mount share"
        exit 1
    fi
fi

# Run rsync
log "Syncing repository to NAS..."
rsync -avh --delete \
    --stats \
    --exclude="locks/" \
    "$SOURCE_REPO/" \
    "${DEST_PATH}/" \
    >> "$LOG_FILE" 2>&1

if [ $? -eq 0 ]; then
    log "Sync completed successfully"
    SYNC_STATUS="success"
else
    log "ERROR: Sync failed"
    exit 1
fi

exit 0
