#!/bin/bash
 
function init {
        if [ -z "`which lsof`" ]; then echo "lsof isn't installed"; return 1; fi
        if [ ! -f ~/qstat ]; then echo "qstat isn't installed"; return 1; fi
        if [ ! -f ~/watchdog_servers ]; then echo "~/watchdog_servers doesn't exists"; return 1; fi
        return 0
}
 
function not_response {
        ~/qstat -a2s $1 -nh -timeout 20 | egrep -q 'no response|DOWN'
}
 
function get_pid {
        lsof -i 4udp@${1} | cut -d ' ' -f2 | tail -n 1
}
 
function parse_list {
        cat watchdog_servers | tr -d \r
}
 
function kill_dead_server {
        echo -en "Testing -> $1\t\t\t"
        if not_response $1; then
                pid=`get_pid $1`
                [[ -z "$pid" ]] && echo "[Not Running]"
                [[ ! -z "$pid" ]] && kill $pid && echo "[Restarted]"
        else
        echo "[OK]"
        fi
}
 
init || exit
for server in `parse_list`; do
        kill_dead_server $server
done