#!/bin/bash

# Mintel Directus Sync Engine
# Synchronizes Directus Data (Postgres + Uploads) between Local and Remote

REMOTE_HOST="${SSH_HOST:-root@alpha.mintel.me}"
ACTION=$1
ENV=$2

# Help
if [ -z "$ACTION" ] || [ -z "$ENV" ]; then
    echo "Usage: mintel-sync [push|pull] [testing|staging|production]"
    echo ""
    echo "Commands:"
    echo "  push   Sync LOCAL data -> REMOTE"
    echo "  pull   Sync REMOTE data -> LOCAL"
    echo ""
    echo "Environments:"
    echo "  testing, staging, production"
    exit 1
fi

PRJ_ID=$(jq -r .name package.json | sed 's/@mintel\///')
case $ENV in
  testing)    PROJECT_NAME="${PRJ_ID}-testing"; ENV_FILE=".env.testing" ;;
  staging)    PROJECT_NAME="${PRJ_ID}-staging"; ENV_FILE=".env.staging" ;;
  production) PROJECT_NAME="${PRJ_ID}-prod";    ENV_FILE=".env.prod"    ;;
  *) echo "❌ Invalid environment: $ENV"; exit 1 ;;
esac

REMOTE_DIR="/home/deploy/sites/${PRJ_ID}.com"

# DB Details
DB_USER="directus"
DB_NAME="directus"

echo "🔍 Detecting local database..."
LOCAL_DB_CONTAINER=$(docker compose ps -q directus-db)
if [ -z "$LOCAL_DB_CONTAINER" ]; then
    echo "❌ Local directus-db container not found. Running?"
    exit 1
fi

if [ "$ACTION" == "push" ]; then
    echo "🚀 Pushing LOCAL -> $ENV ($PROJECT_NAME)..."
    docker exec "$LOCAL_DB_CONTAINER" pg_dump -U "$DB_USER" --clean --if-exists --no-owner --no-privileges "$DB_NAME" > dump.sql
    scp dump.sql "$REMOTE_HOST:$REMOTE_DIR/dump.sql"
    
    REMOTE_DB_CONTAINER=$(ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME ps -q directus-db")
    ssh "$REMOTE_HOST" "docker exec -i $REMOTE_DB_CONTAINER psql -U $DB_USER $DB_NAME < $REMOTE_DIR/dump.sql"
    
    rsync -avz --progress ./directus/uploads/ "$REMOTE_HOST:$REMOTE_DIR/directus/uploads/"
    rm dump.sql
    ssh "$REMOTE_HOST" "rm $REMOTE_DIR/dump.sql"
    echo "✨ Push complete!"

elif [ "$ACTION" == "pull" ]; then
    echo "📥 Pulling $ENV -> LOCAL..."
    REMOTE_DB_CONTAINER=$(ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME ps -q directus-db")
    ssh "$REMOTE_HOST" "docker exec $REMOTE_DB_CONTAINER pg_dump -U $DB_USER --clean --if-exists --no-owner --no-privileges $DB_NAME > $REMOTE_DIR/dump.sql"
    scp "$REMOTE_HOST:$REMOTE_DIR/dump.sql" dump.sql
    
    docker exec -i "$LOCAL_DB_CONTAINER" psql -U "$DB_USER" "$DB_NAME" < dump.sql
    rsync -avz --progress "$REMOTE_HOST:$REMOTE_DIR/directus/uploads/" ./directus/uploads/
    rm dump.sql
    ssh "$REMOTE_HOST" "rm $REMOTE_DIR/dump.sql"
    echo "✨ Pull complete!"
fi
