#!/bin/bash

# Function to kill the previous cargo process
kill_cargo() {
  if [ -n "$pid" ] && ps -p $pid > /dev/null; then
    echo "Terminating previous cargo process..."
    pkill -P $pid
    kill -TERM $pid 2>/dev/null
    wait $pid 2>/dev/null
  fi
}

# Cleanup on script exit
trap 'kill_cargo; echo "Monitor stopped."; exit' INT TERM EXIT

echo "Monitoring directory for changes..."
echo "Press Ctrl+C to exit"

# Initial run
cargo r &
pid=$!

# Check if we're on macOS
if [[ "$(uname)" == "Darwin" ]]; then
  # Use fswatch for macOS
  fswatch -o src/ assets/ | while read; do
    echo -e "\n--- Changes detected, restarting cargo r ---"

    # Kill the previous cargo process
    kill_cargo

    # Start a new cargo process
    cargo r &
    pid=$!
  done
else
  # Use inotifywait for Linux
  while true; do
    # Wait for changes in the directory
    inotifywait -q -e modify,create,delete,move -r src/ assets/ 2>/dev/null

    echo -e "\n--- Changes detected, restarting cargo r ---"

    # Kill the previous cargo process
    kill_cargo

    # Start a new cargo process
    cargo r &
    pid=$!
  done
fi

