#!/usr/bin/ruby

require "socket"

# for native ruby DNS SRV
require "resolv"

server = "tss_server"
dump_all = false

ARGV.each { |a|
    case a
    	when /-v/
	    dump_all = true
    end
}

def get_srv_info ( name )
    name = name.downcase.gsub(/_/,"-")
    srvname = "_" + name + "._tcp.mmto.arizona.edu"
    begin
	rr = Resolv::DNS.open.getresource( srvname, Resolv::DNS::Resource::IN::SRV )
    rescue Resolv::ResolvError
	return nil
    end
    return nil unless rr
    rv = Hash.new
    rv[:name] = name
    rv[:host] = rr.target.to_s
    rv[:port] = rr.port
    return rv
end

def check_socket ( host, port )
    begin
	sock = TCPSocket.open( host, port )
	print "Connection Accepted on port #{port}\n"
	return sock
    rescue Errno::ECONNREFUSED
	print "Connection Refused on port #{port}\n"
	return nil
    rescue => why
	print "Connection to port #{port} failed: #{why}\n"
	return nil
    end
end

def get_cmd ( sock, cmd )

    sock.print cmd + "\n"

    rv = Array.new
    loop do
	begin
	    x = sock.readline
	rescue EOFError
	    break
	end
	break if x =~ /^.EOF/
	rv << x.chomp
    end
    return rv
end

srv = get_srv_info server

unless srv
    print "SRV lookup for #{server} fails\n"
    exit
end

host = srv[:host]
port = srv[:port]

s = check_socket host, port
unless s
    print "#{server} does not seem to be running on host: #{host} port #{port}\n"
    print "maybe try: mmtserv tss_server restart\n"
    exit
end

print "#{server} is running on host: #{host} port #{port}\n"

reply = get_cmd s, "get_eof tss_server_count"
unless reply.size == 1
    print "The TSS server is running, but is screwed up big time\n"
    exit
end
count = reply[0]

all_reply = get_cmd s, "all"
unless all_reply.size >= 60
    print "All command strangely returns only #{all_reply.size} values (61 or more expected)\n"
    print "TSS server is running, but not getting data from TSS\n"
    exit
end
print "ALL command from tss server looks good\n"
print "tss_server_count is: ", count, "\n"

reply = get_cmd s, "get_eof tss_status"
unless reply.size == 1
    print "Cannot get value for tss_status\n"
    exit
end
tss_status = reply[0]
print "tss_status is: ", tss_status, "\n"
if tss_status == "NA"
    print "A value of NA indicates the server is not getting updates from the TSS\n"
end

if dump_all
	all_reply.each { |x|
		puts x
	}
end

# THE END
