#!/bin/env python

from string import lower, split
from sys import argv, exit
from os import getenv
import socket

program = 'mk5command'
version = '0.2'
author  = 'Walter Brisken <wbrisken@nrao.edu>'
verdate = '20080613'

defaultDifxMessagePort = 50200
defaultDifxMessageGroup = '224.2.2.1'

def usage(pgm):
	print '%s ver. %s  %s %s\n' % (program, version, author, verdate)
	print 'A program that talks to the mk5daemon programs running on the'
	print 'software correlator computers, including the mark5s.\n'
	print 'usage : %s <command> <machines>\n' % pgm
	print '<command> can be one of the following (case insensitive):'
	print '  GetVSN -- tell Mark5 unit to report is modules'
	print '  ResetMark5 -- runs SSReset followed by ssopen on Mark5'
	print '  StartMark5A -- starts the Mark5A program'
	print '  StopMark5A -- stops the Mark5A program'
	print '  Reboot -- reboots the machine'
	print '  Poweroff -- powers off the machine'
	print '  Clear -- used to clear errant "busy" state'
	print '  stopmk5daemon -- tell the mk5daemon program to quit\n'
	print '<machines> is a list of cluster members to receive the message;'
	print '  the format is as follows:'
	print '    general: the explicit computer hostname, or "all" for all'
	print '    mark5 units:  01 through 24, or "mark5" for all'
	print '    processor node:  000 though 999, or "swc" for all'
	print '    ranges are allowed:  12-18 or 001-010\n'
	

def sendCommand(cmd, units, verbose):
	src = socket.gethostname()
	dest = ''
	for u in units:
		if lower(u) == 'all':
			name = 'all'
		elif len(u) == 2:
			name = 'mark5fx' + u
		elif len(u) == 3:
			name = 'swc' + u
		else:
			name = u
		dest += '<to>%s</to>' % name
	message = \
	  '<?xml version="1.0" encoding="UTF-8"?>\n' \
	  '<difxMessage>' \
	    '<header>' \
	      '<from>%s</from>' \
	      '%s' \
	      '<mpiProcessId>-1</mpiProcessId>' \
	      '<identifier>mk5control</identifier>' \
	      '<type>DifxCommand</type>' \
	    '</header>' \
	    '<body>' \
	      '<seqNumber>0</seqNumber>' \
	      '<difxCommand>' \
	        '<command>%s</command>' \
	      '</difxCommand>' \
	    '</body>' \
	  '</difxMessage>' % (src, dest, cmd)

	if verbose:
		print message

	port = getenv('DIFX_MESSAGE_PORT')
	if port == None:
		port = defaultDifxMessagePort
	else:
		port = int(port)
	group = getenv('DIFX_MESSAGE_GROUP')
	if group == None:
		group = defaultDifxMessageGroup

	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
	sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
	sock.sendto(message, (group, port))

if len(argv) < 3:
	usage(argv[0])
	exit(0)

machines = []
for a in argv[2:]:
	s = split(a, '-')
	if len(s) == 1:
		machines.append(a)
	elif len(s) == 2:
		if len(s[0]) != len(s[1]):
			print 'bad syntax: ', a
			exit(0)
		m = int(s[0])
		n = int(s[1])
		if len(s[0]) == 2:
			for i in range(m, n+1):
				machines.append('%02d' % i)
		elif len(s[0]) == 3:
			for i in range(m, n+1):
				machines.append('%03d' % i)
		else:
			print 'bad syntax: ', a
			exit(0)

sendCommand(argv[1], machines, False)