#!/bin/bash

# Generic PostgreSQL service migration script
# Usage: ./migrate_service.sh <service_name> <old_host> <old_port> <old_user> <old_password> <old_db>

set -e

if [ "$#" -ne 6 ]; then
    echo "Usage: $0 <service_name> <old_host> <old_port> <old_user> <old_password> <old_db>"
    exit 1
fi

SERVICE_NAME=$1
OLD_HOST=$2
OLD_PORT=$3
OLD_USER=$4
OLD_PASSWORD=$5
OLD_DB=$6

# Map service names to database names and users
case $SERVICE_NAME in
    synapse)
        NEW_DB="synapse"
        NEW_USER="synapse_user"
        NEW_PASSWORD="${SYNAPSE_POSTGRES_PASSWORD}"
        ;;
    mas)
        NEW_DB="mas"
        NEW_USER="mas_user"
        NEW_PASSWORD="${MAS_POSTGRES_PASSWORD}"
        ;;
    signal)
        NEW_DB="signal"
        NEW_USER="signal_user"
        NEW_PASSWORD="${MAUTRIX_SIGNAL_POSTGRES_PASSWORD}"
        ;;
    whatsapp)
        NEW_DB="whatsapp"
        NEW_USER="whatsapp_user"
        NEW_PASSWORD="${MAUTRIX_WHATSAPP_POSTGRES_PASSWORD}"
        ;;
    paperless)
        NEW_DB="paperless"
        NEW_USER="paperless_user"
        NEW_PASSWORD="${PAPERLESS_POSTGRES_PASSWORD}"
        ;;
    immich)
        NEW_DB="immich"
        NEW_USER="immich_user"
        NEW_PASSWORD="${IMMICH_POSTGRES_PASSWORD}"
        ;;
    shlink)
        NEW_DB="shlink"
        NEW_USER="shlink_user"
        NEW_PASSWORD="${SHLINK_POSTGRES_PASSWORD}"
        ;;
    spliit)
        NEW_DB="spliit"
        NEW_USER="spliit_user"
        NEW_PASSWORD="${SPLIIT_POSTGRES_PASSWORD}"
        ;;
    audiomuse)
        NEW_DB="audiomuse"
        NEW_USER="audiomuse_user"
        NEW_PASSWORD="${AUDIOMUSE_POSTGRES_PASSWORD}"
        ;;
    *)
        echo "Unknown service: $SERVICE_NAME"
        exit 1
        ;;
esac

echo "Starting migration for $SERVICE_NAME to database $NEW_DB..."

# Export from old database
echo "Exporting data from $OLD_DB..."
PGPASSWORD="$OLD_PASSWORD" pg_dump \
    -h "$OLD_HOST" \
    -p "$OLD_PORT" \
    -U "$OLD_USER" \
    -d "$OLD_DB" \
    -F custom \
    -f "/tmp/${SERVICE_NAME}_dump.custom"

# Import to new database
echo "Importing data to $NEW_DB database..."
PGPASSWORD="$NEW_PASSWORD" pg_restore \
    -h localhost \
    -p 5432 \
    -U "$NEW_USER" \
    -d "$NEW_DB" \
    --clean \
    --if-exists \
    "/tmp/${SERVICE_NAME}_dump.custom"

echo "Migration completed for $SERVICE_NAME!"

# Clean up
rm -f "/tmp/${SERVICE_NAME}_dump.custom"

echo "You can now update your $SERVICE_NAME service configuration to use:"
echo "  Host: localhost"
echo "  Port: 5432"
echo "  Database: $NEW_DB"
echo "  User: $NEW_USER"
echo "  Password: ***"