Tags
#!/bin/bash
# Script Version: 1.0
# Description: This script searches through BorgBackup archives for files matching a specific pattern.

set -euo pipefail

# Variables
HOSTNAME=$(hostname)
BORG_PASSPHRASE_FILE="$HOME/.borg_passphrase"
SSH_KEY="/root/.ssh/id_ed25519_$HOSTNAME"
REPO1=".at:/./borg"
LOG="/var/log/borg_find.log"
PATTERN="${1:-}" # File pattern to search for (provided as the first argument)

# Load Borg passphrase
if [ -f "$BORG_PASSPHRASE_FILE" ]; then
  export BORG_PASSPHRASE=$(cat "$BORG_PASSPHRASE_FILE")
else
  echo "Passphrase file not found: $BORG_PASSPHRASE_FILE"
  exit 1
fi

# Function to log messages
log_message() {
  echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" >> "$LOG"
}

# Function to send an email with error message
send_error_mail() {
  ERROR_MSG=$1
  echo "$ERROR_MSG" | mail -s "Borg Find Error on $HOSTNAME" root
  log_message "$ERROR_MSG"
}

# Ensure a pattern is provided
if [ -z "$PATTERN" ]; then
  echo "Usage: $0 <file-pattern>"
  exit 1
fi

# Function to search for files in Borg repository
find_files() {
  log_message "Starting search for files matching pattern: $PATTERN"
  borg list "$REPO1" --rsh="ssh -i $SSH_KEY" | awk '{print $1}' | while read -r archive; do
    log_message "Searching in archive: $archive"
    if borg list "$REPO1::$archive" --rsh="ssh -i $SSH_KEY" | grep "$PATTERN"; then
      log_message "Found matching files in archive: $archive"
    else
      log_message "No matches found in archive: $archive"
    fi
  done
  log_message "Search completed."
}

# Main process
log_message "Borg find file process started."
find_files
log_message "Borg find file process completed."

# Unset sensitive variables
unset BORG_PASSPHRASE