#!/bin/bash

# Script to dump icon and icon_groups tables from PostgreSQL database
# Usage: ./dump-icons.sh [output_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}"

# Output file name (default: icons_dump_YYYYMMDD_HHMMSS.sql)
if [ -z "$1" ]; then
  TIMESTAMP=$(date +%Y%m%d_%H%M%S)
  OUTPUT_FILE="icons_dump_${TIMESTAMP}.sql"
else
  OUTPUT_FILE="$1"
fi

echo "Dumping icon_groups and icons tables..."
echo "Database: ${DB_NAME}@${DB_HOST}:${DB_PORT}"
echo "Output file: ${OUTPUT_FILE}"

# Dump icon_groups table first (parent table)
echo "Dumping icon_groups table..."
PGPASSWORD="${DB_PASS}" pg_dump \
  -h "${DB_HOST}" \
  -p "${DB_PORT}" \
  -U "${DB_USER}" \
  -d "${DB_NAME}" \
  -t icon_groups \
  --data-only \
  --column-inserts \
  --no-owner \
  --no-privileges \
  > "${OUTPUT_FILE}"

# Append icons table to the dump file
echo "Dumping icons table..."
PGPASSWORD="${DB_PASS}" pg_dump \
  -h "${DB_HOST}" \
  -p "${DB_PORT}" \
  -U "${DB_USER}" \
  -d "${DB_NAME}" \
  -t icons \
  --data-only \
  --column-inserts \
  --no-owner \
  --no-privileges \
  >> "${OUTPUT_FILE}"

echo "Dump completed successfully!"
echo "File saved to: ${OUTPUT_FILE}"
echo ""
echo "To restore, run: ./restore-icons.sh ${OUTPUT_FILE}"

