##cd /var/www/html/trackmeetweb.shardatech.org
##/usr/bin/npx expo serve dist --port 3508

#!/bin/bash

# App Details
APP_DIR="/var/www/html/trackmeetweb.shardatech.org"
APP_MAIN="expo serve dist --port 3508"
PORT=3508
LOG_DIR="$APP_DIR/logs"
APP_LOG="$LOG_DIR/app.log"
CRON_LOG="$LOG_DIR/start-trackmeetweb-node.log"

# Ensure log directory exists
mkdir -p "$LOG_DIR"

echo "$(date): Restart script triggered" >> "$CRON_LOG"

# Kill only the process listening on the specific port and running from this APP_DIR
PIDS=$(lsof -t -i:$PORT -sTCP:LISTEN | xargs -r ps -o pid,cmd --no-headers -p | grep "$APP_DIR" | awk '{print $1}')
if [ ! -z "$PIDS" ]; then
  echo "$PIDS" | xargs kill
  echo "$(date): Killed process(es) with PID(s): $PIDS" >> "$CRON_LOG"
else
  echo "$(date): No existing process found to kill on port $PORT" >> "$CRON_LOG"
fi

# Navigate to app directory
cd "$APP_DIR" || {
  echo "$(date): Failed to cd to $APP_DIR" >> "$CRON_LOG"
  exit 1
}

# Start Node app with nohup in background
nohup /usr/bin/npx $APP_MAIN > "$APP_LOG" 2>&1 &
NEW_PID=$!
sleep 2

# Check if the process started successfully
if ps -p $NEW_PID > /dev/null; then
  echo "$(date): Node process started successfully with PID $NEW_PID" >> "$CRON_LOG"
else
  echo "$(date): Failed to start Node process" >> "$CRON_LOG"
fi
