#!/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"
MOUNT_POINT="/mnt/truenas/backups"
MOUNT_TIMEOUT=30

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

# Export password
export RESTIC_PASSWORD_FILE

# 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="$(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 "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

# Verify mount is accessible
if [ ! -d "$RESTIC_REPOSITORY" ]; then
    log "ERROR: Repository directory not accessible at $RESTIC_REPOSITORY"
    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
