#!/usr/bin/env bash
# DBeaver Profile Restore Script
# This script restores a DBeaver backup created with the backup script

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

# DBeaver configuration location
DBEAVER_DATA="$HOME/.local/share/DBeaverData"

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

# Check if backup file exists
if [ ! -f "$BACKUP_DIR/$BACKUP_FILE" ]; then
	echo "Error: Backup file not found at $BACKUP_DIR/$BACKUP_FILE" | tee -a "$LOG_FILE"
	exit 1
fi

# Check if DBeaver data directory exists and create backup if it does
if [ -d "$DBEAVER_DATA" ]; then
	echo "DBeaver data directory exists. Creating backup before restoration..." | tee -a "$LOG_FILE"
	TEMP_BACKUP="${DBEAVER_DATA}_backup_$(date +%Y%m%d_%H%M%S)"
	mv "$DBEAVER_DATA" "$TEMP_BACKUP"
	echo "Original data backed up to: $TEMP_BACKUP" | tee -a "$LOG_FILE"
fi

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

# Extract backup file
echo "Extracting backup archive..." | tee -a "$LOG_FILE"
tar -xzf "$BACKUP_DIR/$BACKUP_FILE" -C "$TEMP_DIR"
EXTRACT_RESULT=$?

if [ $EXTRACT_RESULT -ne 0 ]; then
	echo "Error: Failed to extract backup with exit code $EXTRACT_RESULT" | tee -a "$LOG_FILE"
	rm -rf "$TEMP_DIR"
	exit 1
fi

# Create target directory if it doesn't exist
mkdir -p "$(dirname "$DBEAVER_DATA")"

# Copy extracted content to DBeaver data directory
echo "Restoring DBeaver data to $DBEAVER_DATA..." | tee -a "$LOG_FILE"
cp -r "$TEMP_DIR/DBeaverData" "$(dirname "$DBEAVER_DATA")/"
RESTORE_RESULT=$?

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

# Check if restore was successful
if [ $RESTORE_RESULT -eq 0 ]; then
	echo "Restore completed successfully to: $DBEAVER_DATA" | tee -a "$LOG_FILE"
	echo "You may need to restart DBeaver for changes to take effect." | tee -a "$LOG_FILE"
else
	echo "Error: Restore failed with exit code $RESTORE_RESULT" | tee -a "$LOG_FILE"
	if [ -d "$TEMP_BACKUP" ]; then
		echo "Attempting to restore original data from backup..." | tee -a "$LOG_FILE"
		rm -rf "$DBEAVER_DATA"
		mv "$TEMP_BACKUP" "$DBEAVER_DATA"
		echo "Original data restored from backup." | tee -a "$LOG_FILE"
	fi
fi

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