#!/bin/bash

# Script to restore icon and icon_groups tables to PostgreSQL database
# Usage: ./restore-icons.sh [dump_file]

set -e

# Load environment variables if .env file exists
if [ -f .env ]; then
  set -a
  # Source .env file, handling comments and empty lines
  while IFS= read -r line || [ -n "$line" ]; do
    # Remove leading/trailing whitespace
    line=$(echo "$line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    # Skip empty lines and lines starting with #
    [[ -z "$line" ]] && continue
    [[ "$line" =~ ^# ]] && continue
    # Remove inline comments (everything after # that's not in quotes)
    line=$(echo "$line" | sed 's/#.*$//' | sed 's/[[:space:]]*$//')
    # Skip if line is empty after removing comments
    [[ -z "$line" ]] && continue
    # Export the variable (only if it looks like KEY=VALUE)
    if [[ "$line" =~ ^[[:alpha:]_][[:alnum:]_]*= ]]; then
      export "$line" 2>/dev/null || true
    fi
  done < .env
  set +a
fi

# Get database connection details from environment variables
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-dmenu}"
DB_USER="${DB_USER:-postgres}"

# Input file name
if [ -z "$1" ]; then
  echo "Error: Please provide a dump file to restore"
  echo "Usage: ./restore-icons.sh <dump_file>"
  echo "Example: ./restore-icons.sh icons_dump_20240101_120000.sql"
  exit 1
fi

DUMP_FILE="$1"

# Check if dump file exists
if [ ! -f "${DUMP_FILE}" ]; then
  echo "Error: Dump file '${DUMP_FILE}' not found!"
  exit 1
fi

echo "Restoring icon_groups and icons tables..."
echo "Database: ${DB_NAME}@${DB_HOST}:${DB_PORT}"
echo "Dump file: ${DUMP_FILE}"
echo ""

# Ask for confirmation
read -p "This will replace existing data in icon_groups and icons tables. Continue? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Restore cancelled."
  exit 0
fi

# Disable foreign key checks temporarily and truncate tables
echo "Clearing existing data..."
PGPASSWORD="${DB_PASS}" psql \
  -h "${DB_HOST}" \
  -p "${DB_PORT}" \
  -U "${DB_USER}" \
  -d "${DB_NAME}" \
  -c "TRUNCATE TABLE icons CASCADE;" \
  -c "TRUNCATE TABLE icon_groups CASCADE;"

# Restore data from dump file
echo "Restoring data from ${DUMP_FILE}..."
PGPASSWORD="${DB_PASS}" psql \
  -h "${DB_HOST}" \
  -p "${DB_PORT}" \
  -U "${DB_USER}" \
  -d "${DB_NAME}" \
  -f "${DUMP_FILE}"

echo ""
echo "Restore completed successfully!"
echo ""

# Verify the restore
echo "Verifying restore..."
ICON_GROUPS_COUNT=$(PGPASSWORD="${DB_PASS}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -t -c "SELECT COUNT(*) FROM icon_groups;")
ICONS_COUNT=$(PGPASSWORD="${DB_PASS}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -t -c "SELECT COUNT(*) FROM icons;")

echo "icon_groups records: ${ICON_GROUPS_COUNT}"
echo "icons records: ${ICONS_COUNT}"

