#!/bin/bash
# Watchdog script to keep WhatsApp Baileys service alive 24/7 on cPanel Shared Hosting

APP_DIR="/home/ypdsalhi/repositories/whatsapp-service"
NODE_BIN="/home/ypdsalhi/nodevenv/repositories/whatsapp-service/18/bin/node"

# Fallback if node binary is in PATH or different nodevenv
if [ ! -f "$NODE_BIN" ]; then
    NODE_BIN=$(which node)
fi

cd "$APP_DIR" || exit 1

# Check if WhatsApp service is responsive on port 3000
if ! curl -s --max-time 3 http://127.0.0.1:3000/status | grep -q "status"; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] WhatsApp Service DOWN. Restarting..." >> "$APP_DIR/watchdog.log"
    # Clean any hung zombie processes on port 3000 before restart
    pkill -9 -f "server.js" > /dev/null 2>&1
    sleep 1
    nohup "$NODE_BIN" server.js >> "$APP_DIR/out.log" 2>&1 &
fi