#!/usr/bin/env bash
# Run any Node script in the background (survives terminal disconnect).
# Logs to logs/<script-name>-YYYYMMDD-HHMMSS.log
#
# Usage:
#   ./scripts/run-in-background.sh src/scripts/sync-mysql-hotels-to-opensearch.js --full-sync --cities-from-db
#   ./scripts/run-in-background.sh src/index.js --run

set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT"

if [ $# -eq 0 ]; then
  echo "Usage: $0 <node-script> [args...]"
  echo "Example: $0 src/scripts/sync-mysql-hotels-to-opensearch.js --full-sync --cities-from-db"
  exit 1
fi

NODE_SCRIPT="$1"
shift
ARGS=("$@")
BASENAME=$(basename "$NODE_SCRIPT" .js)
mkdir -p logs
LOGFILE="logs/${BASENAME}-$(date +%Y%m%d-%H%M%S).log"

nohup node "$NODE_SCRIPT" "${ARGS[@]}" >> "$LOGFILE" 2>&1 &
PID=$!

echo "Started in background."
echo "  PID:  $PID"
echo "  Log:  $LOGFILE"
echo ""
echo "  Watch: tail -f $LOGFILE"
echo "  Stop:  kill $PID"
