#!/bin/bash

function init {
	[[ `which lsof` ]] || echo "lsof isn't installed" || return 1
	[[ -f ~/qstat ]] || echo "qstat isn't installed" || return 1
	[[ -f ~/watchdog_servers ]] || echo "~/watchdog_servers doesn't exists" || return 1
	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
