#!/bin/bash
cd /home/z/my-project
while true; do
  if ! ss -tlnp 2>/dev/null | grep -q ':3000'; then
    echo "[$(date)] Starting dev server..." >> /home/z/my-project/dev.log
    npx next dev -p 3000 >> /home/z/my-project/dev.log 2>&1 &
    SERVER_PID=$!
    echo "[$(date)] Server PID: $SERVER_PID" >> /home/z/my-project/dev.log
    # Wait for server to start
    for i in $(seq 1 30); do
      if ss -tlnp 2>/dev/null | grep -q ':3000'; then
        echo "[$(date)] Server is listening on 3000" >> /home/z/my-project/dev.log
        break
      fi
      sleep 1
    done
    # Keep checking if server is alive
    while kill -0 $SERVER_PID 2>/dev/null; do
      sleep 5
    done
    echo "[$(date)] Server died, restarting in 3 seconds..." >> /home/z/my-project/dev.log
    sleep 3
  else
    sleep 10
  fi
done
