File: //bigscoots/wpo/backups/vm_backup_manager.sh
#!/bin/bash
# Parse arguments
HOSTNAME_TO_FIND=""
while [[ "$#" -gt 0 ]]; do
case $1 in
--hostname) HOSTNAME_TO_FIND="$2"; shift ;;
*) echo "Unknown parameter passed: $1"; exit 1 ;;
esac
shift
done
# Check if hostname is provided
if [ -z "$HOSTNAME_TO_FIND" ]; then
echo "Usage: bash list_backups.sh --hostname <hostname>"
exit 1
fi
# Create a temporary file for storing the result data
tmp_file=$(mktemp)
# Initialize the temporary file with an empty result object
echo '{"errors": [], "messages": [], "success": false, "result": {}}' > "$tmp_file"
# Function to log messages to the response
log_message() {
local message="$1"
jq --arg msg "$message" '.messages += [$msg]' "$tmp_file" > "$tmp_file.tmp" && mv "$tmp_file.tmp" "$tmp_file"
}
# Function to log errors to the response
log_error() {
local error="$1"
jq --arg err "$error" '.errors += [$err]' "$tmp_file" > "$tmp_file.tmp" && mv "$tmp_file.tmp" "$tmp_file"
}
# Function to add a backup file info and store it in the result under the hostname key
add_result() {
local hostname="$1"
local date="$2"
local size="$3"
local path="$4"
# Debugging: Print what's being added
#echo "Adding result for $hostname: date=$date, size=$size, path=$path"
# Construct the backup object
backup_entry=$(jq -n --arg date "$date" --arg size "$size" --arg path "$path" \
'{ "date": $date, "size": $size, "path": $path }')
# Add the result under the hostname key in the temp file
jq --arg hostname "$hostname" --argjson entry "$backup_entry" \
'.result[$hostname] |= ( . // [] ) + [$entry]' "$tmp_file" > "$tmp_file.tmp" && mv "$tmp_file.tmp" "$tmp_file"
}
# Function to check backup files on each server
check_backup_servers() {
mapfile -t hosts < <(grep backup /etc/hosts | awk '{print $1, $2}')
for host in "${hosts[@]}"; do
IP=$(echo "$host" | awk '{print $1}')
HOSTNAME=$(echo "$host" | awk '{print $2}')
log_message "Checking backups on $IP ($HOSTNAME)..."
# Capture the output of the SSH command
backup_files=$(ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p 2222 "$IP" "find /home/bigscoots/vps/ -type f -name '*$HOSTNAME_TO_FIND*' -exec ls -lah {} \;" </dev/null 2>/dev/null)
if [ $? -ne 0 ]; then
log_error "Failed to connect to $IP ($HOSTNAME)"
continue
fi
if [ -n "$backup_files" ]; then
echo "$backup_files" | while read -r line; do
size=$(echo "$line" | awk '{print $5}')
date=$(echo "$line" | awk '{print $6, $7, $8}')
path=$(echo "$line" | awk '{print $9}')
if [ -n "$size" ] && [ -n "$date" ] && [ -n "$path" ]; then
add_result "$HOSTNAME" "$date" "$size" "$path"
fi
done
else
log_message "No backup files found on $IP ($HOSTNAME)"
fi
done
# Mark the response as successful
jq '.success = true' "$tmp_file" > "$tmp_file.tmp" && mv "$tmp_file.tmp" "$tmp_file"
}
# Main script execution
check_backup_servers
# Output the final JSON response
cat "$tmp_file" | jq
# Clean up the temporary file
rm "$tmp_file"