#!/data/data/com.termux/files/usr/bin/bash
#
# SMS API Server Watchdog
# Monitors the Flask server and restarts it if it crashes.
# Run this from ~/.termux/boot/start-sms-server or manually.
#

SERVER_SCRIPT="$HOME/sms-server/android/termux-sms-api-server.py"
LOG_DIR="$HOME/logs"
LOG_FILE="$LOG_DIR/sms-api.log"
PID_FILE="$LOG_DIR/sms-api.pid"
CHECK_INTERVAL=30  # seconds between health checks

# Source environment variables (SMS_API_SECRET etc.)
# Non-interactive shells (nohup, boot scripts) don't source .bashrc automatically
[ -f "$HOME/.bashrc" ] && . "$HOME/.bashrc"

mkdir -p "$LOG_DIR"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [watchdog] $1" >> "$LOG_FILE"
    echo "[watchdog] $1"
}

start_server() {
    if [ -f "$PID_FILE" ]; then
        local old_pid
        old_pid=$(cat "$PID_FILE")
        if kill -0 "$old_pid" 2>/dev/null; then
            log "Server already running (PID $old_pid)"
            return 0
        fi
    fi

    log "Starting SMS API server..."
    nohup python "$SERVER_SCRIPT" >> "$LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    log "Server started (PID $!)"
    sleep 3  # Give it time to start
}

check_health() {
    curl -s --max-time 5 http://127.0.0.1:5001/health > /dev/null 2>&1
    return $?
}

# Acquire wake lock to prevent Android from killing us
termux-wake-lock 2>/dev/null

log "Watchdog starting..."
start_server

# Main watchdog loop
while true; do
    sleep "$CHECK_INTERVAL"

    if ! check_health; then
        log "Health check FAILED — restarting server"

        # Kill old process if it exists
        if [ -f "$PID_FILE" ]; then
            kill "$(cat "$PID_FILE")" 2>/dev/null
            sleep 2
        fi

        # Also kill any orphaned instances
        pkill -f "termux-sms-api-server.py" 2>/dev/null
        sleep 1

        start_server

        if check_health; then
            log "Server restarted successfully"
        else
            log "Server failed to restart — will retry in ${CHECK_INTERVAL}s"
        fi
    fi
done
