###################################################################
##
##     SetiMonClient v 0.9
##   =======================
##
##  autor: dejf  (dejf@ruchoporu.org)
##  (c) RuchOporu.org 2003
##
##  Niniejszy program jak i idea seti monitora jest
##  wlasnoscia RuchuOporu. Program moze byc wykorzystywany
##  wylacznie przez bojownikow RuchuOporu i tylko na potrzeby
##  Ruchu. Modyfikacja kodu mozliwa wylacznie za zgoda
##  Rady Najwyzszej Ruchu Oporu.
##
##  Uzwanie programu na ternie USA oraz innych krajow
##  smierdzacych z daleka ufolami jest zakazane.
##
##  "Tylko kisielem splynie prawda!!!"
##  http://ruchoporu.org   ruchoporu@ruchoporu.org
##
###################################################################





###################################################################
########################  POMOC  ##################################
###################################################################


def help():

        """RO SetMon Client 0.9alpha

	Program czyta aktulny stan obliczen wskazanej jednostki Seti i wysyla wyniki na serwer Ruchu Oporu.
	Dzieki temu mozliwe jest sledzenie postepow w obliczeniach calej bojowniczej spolecznosci.

	Parametry programu:
	-d dir lub --seti-dir dir	- katalog klienta seti (domyslnie ".")
	-n nzw lub --computer-name nzw	- nazwa Twojego bojowniczego komputera (domyslnie "")
	-h lub --help           	- pomoc (ktora aktualnie ogladasz)
	-v lub --verbose		- wyswietla dodatkowe informacje w trakcie pracy
	-s lub --single			- jednokrotne wykonanie programu (np. jesli miast wewnetrznej petli
					  chcesz uzywac np. crona)
	--silent			- nie wyswietla jakichkolwiek komunikatow w trakcie pracy (nawet o bledach)
	"""


###################################################################





import httplib, urllib, fileinput, re, time, socket, sys


False = 0
True = 1


SILENT_MODE = False
VERBOSE_MODE = False
SINGLE_MODE = False;

SETI_DIR = "."
COMPUTER_NAME = ""

SERVER_ADDRESS = "ruchoporu.org"
SERVLET_NAME = "/setimon"

EXECUTE_LOOP = True
INTERVAL = 180




##################################################################


def showMsg( msg ):

	global SILENT_MODE
	if not SILENT_MODE:
		print msg


##################################################################


def getParamFromSahFile( filename, param ):

	try:
		for line in fileinput.input( SETI_DIR + "/" + filename ):
			if re.search( param + "=.", line ):
				fileinput.close()
				line = re.sub( param + "=", "", line )
				return re.sub( "\n", "", line )
	except IOError:
		showMsg( "BLAD! Brak pliku: " + SETI_DIR + "/" + filename )
	return None


##################################################################


def readParams():

	progress = getParamFromSahFile( "state.sah", "prog" )
	name = getParamFromSahFile( "user_info.sah", "name" )
	email = getParamFromSahFile( "temp.sah", "email_addr" )
	if not email:
		email = getParamFromSahFile( "user_info.sah", "email_addr" )
	unitno = getParamFromSahFile( "user_info.sah", "nresults" )
	cputime = getParamFromSahFile( "state.sah", "cpu" )
	if progress and name and email and unitno:
		return { 	'email': email, 
				'user': name, 
				'progress': progress, 
				'unitNo': unitno, 
				'computer': COMPUTER_NAME,
				'time': cputime			}

	return None


##################################################################


def sendResults( stateInfo ):

	try:
		params  = urllib.urlencode( stateInfo )
		conn = httplib.HTTPConnection( SERVER_ADDRESS )
		conn.request( "GET", SERVLET_NAME + "?" + params )
		response = conn.getresponse()
		return response.status

	except socket.error:
		showMsg( "BLAD!!! Brak polaczenia z serwerem"  )
		return -1


##################################################################


def about():

	showMsg( "\nSetiMon Client 1.0\n(c) ruchoporu.org\n" )


#################################################################


def hasParam( param ):

	for p in sys.argv:
		if p == param:
			return True
	return False


#################################################################


def getParamValue( paramS, paramL ):

	isValue = False
	for p in sys.argv:
		if p == paramS or p == paramL:
			isValue = True
		elif isValue:
			return p
	return None


#################################################################

def checkParams():

	global EXECUTE_LOOP
	global VERBOSE_MODE
	global SILENT_MODE
	global SETI_DIR
	global COMPUTER_NAME
	global SINGLE_MODE

	if hasParam( "--help" ) or hasParam( "-h" ):
		print help.__doc__
		EXECUTE_LOOP = False
		return 0

	if hasParam( "--seti-dir" ) or hasParam( "-d" ):
		SETI_DIR = getParamValue( "-d", "--seti-dir" )

	if hasParam( "--verbose" ) or hasParam( "-v" ):
		VERBOSE_MODE = True

	if hasParam( "--silent" ):
		SILENT_MODE = True

	if hasParam( "-s" ) or hasParam( "--single" ):
		SINGLE_MODE = True

	if hasParam( "--computer-name" ) or hasParam( "-n" ):
		COMPUTER_NAME = getParamValue( "-n", "--computer-name" )


#################################################################


if len( sys.argv ) > 1:
	checkParams()


about()


while EXECUTE_LOOP:

	try:
		params = readParams()
		if params:
			status = sendResults( params )
			if status != 200 and status != -1:
				showMsg( "BLAD! Informacje nie zostaly wyslane. Prawdopodobnie bledny adres sieciowy" )
		if VERBOSE_MODE:
			showMsg( params )
		if SINGLE_MODE:
			break
		time.sleep( INTERVAL )

	except KeyboardInterrupt:
		break




