#!/bin/bash

# DBeaver Profile Backup Script
# This script creates a backup of DBeaver profiles and configurations

# Configuration variables - modify as needed
BACKUP_DIR="/home/forbi/Sync/Backups"
HOSTNAME=$(hostname)
BACKUP_FILE="dbeaver_backup_${HOSTNAME}.tar.gz"
LOG_FILE="$BACKUP_DIR/dbeaver_backup_log.txt"

# DBeaver configuration location
DBEAVER_DATA="$HOME/.local/share/DBeaverData" # Contains drivers, workspace, and secure storage

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Start logging
echo "===== DBeaver Backup Started at $(date) =====" >>"$LOG_FILE"

# Check if DBeaver configuration exists
if [ ! -d "$DBEAVER_DATA" ]; then
	echo "Error: DBeaver configuration not found at $DBEAVER_DATA. Please make sure DBeaver is installed and has been run at least once." | tee -a "$LOG_FILE"
	exit 1
fi

# Create temporary directory for backup
TEMP_DIR=$(mktemp -d)
echo "Created temporary directory: $TEMP_DIR" >>"$LOG_FILE"

# Copy DBeaver data to temporary directory
echo "Copying DBeaver data from $DBEAVER_DATA..." >>"$LOG_FILE"
cp -r "$DBEAVER_DATA" "$TEMP_DIR/"

# Create compressed archive
echo "Creating backup archive..." >>"$LOG_FILE"
tar -czf "$BACKUP_DIR/$BACKUP_FILE" -C "$TEMP_DIR" .
BACKUP_RESULT=$?

# Clean up temporary directory
echo "Cleaning up temporary files..." >>"$LOG_FILE"
rm -rf "$TEMP_DIR"

# Check if backup was successful
if [ $BACKUP_RESULT -eq 0 ]; then
	echo "Backup completed successfully: $BACKUP_DIR/$BACKUP_FILE" | tee -a "$LOG_FILE"
	echo "Backup size: $(du -h "$BACKUP_DIR/$BACKUP_FILE" | cut -f1)" | tee -a "$LOG_FILE"
	echo "Keeping only the latest backup for this PC ($HOSTNAME)" >>"$LOG_FILE"
else
	echo "Error: Backup failed with exit code $BACKUP_RESULT" | tee -a "$LOG_FILE"
fi

echo "===== DBeaver Backup Finished at $(date) =====" >>"$LOG_FILE"
