#!/bin/bash

# Script to sync localhost MongoDB with Atlas content
# Usage: ./sync_db.sh

set -e  # Exit on any error

echo "Syncing localhost MongoDB with Atlas content..."

# Load environment variables from .env production
if [ ! -f ".env production" ]; then
    echo "Error: .env production file not found in current directory"
    exit 1
fi

# Read variables directly to avoid shell parsing issues with special characters
ATLAS_URI=$(grep '^ATLAS_URI=' ".env production" | cut -d'=' -f2-)
MONGODB_URI=$(grep '^MONGODB_URI=' ".env production" | cut -d'=' -f2-)

# Check if required variables exist
if [ -z "$ATLAS_URI" ]; then
    echo "Error: ATLAS_URI not found in .env production"
    exit 1
fi

if [ -z "$MONGODB_URI" ]; then
    echo "Error: MONGODB_URI not found in .env production"
    exit 1
fi

# Create temp directory for dump
TEMP_DIR=$(mktemp -d)
echo "Using temp directory: $TEMP_DIR"

# Dump from Atlas
echo "Dumping data from Atlas..."
mongodump --uri="$ATLAS_URI" --out="$TEMP_DIR"

# Drop local database and restore
echo "Restoring to localhost..."
mongorestore --uri="$MONGODB_URI" --drop "$TEMP_DIR/simple-ticketing"

# Clean up
rm -rf "$TEMP_DIR"

echo "Sync completed successfully!"