#!/bin/bash
# Keep-alive script for the Next.js dev server
# Restarts the server if it dies

cd /home/z/my-project

while true; do
  if ! ss -tlnp | grep -q ":3000 "; then
    echo "[$(date)] Starting Next.js dev server..." >> /home/z/my-project/dev.log
    node node_modules/.bin/next dev -p 3000 -H 0.0.0.0 >> /home/z/my-project/dev.log 2>&1 &
    NEXT_PID=$!
    echo "[$(date)] Started with PID $NEXT_PID" >> /home/z/my-project/dev.log
    
    # Wait for the process to exit
    wait $NEXT_PID 2>/dev/null
    echo "[$(date)] Process exited with code $?. Restarting in 3s..." >> /home/z/my-project/dev.log
    sleep 3
  else
    sleep 5
  fi
done
