#! /usr/bin/python
"""
#+
# NAME:
#	tiny
# PURPOSE:
#	Couple of trivial Python functions
# CATEGORY:
#	smei/gen/python
# CALLING SEQUENCE:
#	result = keys( a )
#	result = args( a )
#	is_there( k, a )
#	start( x, a )
#	result = run_cmd( cmd, verbose )
#	result = tomb( size )
#	result = which( program )
#	say( csay, wseif, key, message )
# INPUTS:
#	keys:	  a	: sys.argv
#	args:	  a	: sys.argv
#	is_there: a	: sys.argv
#		  k	: keyword (usually starting with dash)
#	start:	  a	: sys.argv
#		  k	: argument (usually of form 'arg=')
#	run_cmd:  cmd	: shell command to be executed
#	 	  verbose : 0 : do not print the command log
#      			    1 : print command log
# OUTPUTS:
#	keys	: result : list of keywords starting with dash (-)
#	args	: result : list of arguments not starting with dash (-)
#	is_there: result : 0 if keyword 'k' is not present in 'a'
#			   1 if keyword 'k' is present in 'a'
#		  result : 0 if 'a' does not contain entry starting with 'k'
#			   1 if 'a' contains entry starting with 'k'
#	start	: result : substring of argument in 'a' trailing 'k'
#			   blank string is 'a' does not contain 'k'
#	run_cmd	: result : command log
# MODIFICATION HISTORY:
#	MAR-2003, Paul Hick (UCSD/CASS)
#	FEB-2004, Paul Hick (UCSD/CASS)
#		Added tomb function
#	APR-2005, Paul Hick (UCSD/CASS)
#		Removed dependence on string module
#	DEC-2005, Paul Hick (UCSD/CASS; pphick@ucsd.edu)
#		Added say.
#-
"""
import os, sys

def keys( a ):

	k = []

	for b in a:

		if b[0] == '-':
			k.append(b)

	return k


def args( a ):

	k = []

	for b in a:

		if b[0] != '-':
			k.append(b)

	return k

def argn( a, n ):

	b = args( a )

	k = ''
	if len(b) > n: k = b[n]

	return k


def is_there( k, a ):

	return a.count(k) != 0

def start( x, a ):

	k = ''

	for b in a:

		if b[0:len(x)] == x:
			k = b[len(x):]
			break

	return k

def run_cmd( cmd, verbose ):
	if verbose: print cmd
	log = (os.popen(cmd)).read()
	if verbose: print log

	return log

def tomb( size ):

	kilo = float(1024)

	tmp = len(size)-1				# Strip of trailing 'B'
	if size[tmp] == 'B':
		size = size[0:tmp]

	tmp = len(size)-1
	if   size[tmp] == 'G':			# Check for trailing 'G','M','k'
		size = float(size[0:tmp])*kilo
	elif size[tmp] == 'M':
		size = float(size[0:tmp])
	elif size[tmp] == 'k':
		size = float(size[0:tmp])/kilo
	else:
		size = float(size)/(kilo*kilo)

	return size

def count_instances( name, verbose ):

	#name = (os.path.split(argv[0]))[1]+' '+argv[1]

	proc = run_cmd( 'ps -efw | grep "'+name+'"', 0 )
	proc = proc.split('\n')

	cnt = 0
	for p in proc:
		#if p.find('python') != -1 and p.find(name) != -1:
		#if p.find(name) != -1:
		#if p.find(name) != -1 and p.find('grep') == -1:
		if name in p and not 'grep' in p:
			cnt += 1
			if verbose:
				print p

	print '%d'%cnt,'instance(s) running:', name

	return cnt

def dict_entry( args, name, def_value ):

	if args.has_key(name):
		value = args[name]
		if value == '':
			value = def_value
	else:
		value = def_value

	return value

def hide_env( spec ):

	match_name  = ''
	match_value = ''

	for name, value in os.environ.iteritems():
		n = len(value)
		if n != 0:

			# KLUDGE:
			# Checking for the existence of NFS mounts that are not on line,
			# will cause os.path.isdir to freeze the process until there is a
			# timeout. So we don't check for those.

			exists = value.find('/smeidb') == 0 or value.find('/smeidc/') == 0
			if not exists:
				exists = os.path.isdir(value)

			if exists:
				if spec.find(value) == 0:
					if n > len(match_value):
						match_name  = name
						match_value = value

	if match_name == '':
		rtn = spec
	else:
		rtn = '$'+match_name+spec[len(match_value):]

	return rtn

def which( program ):

	rtn = (os.popen('which '+program+' 2> /dev/null').read().split('\n'))[0]

	return rtn

def say( csay, wseif, key, message ):

	from time import strftime

	if key[0] == '#':
		prefix = hide_env(key[1:])
	elif key == '<time>':
		prefix = strftime('%Y/%m/%d %H:%M:%S')
	else:
		prefix = key

	prefix = csay+'-'+wseif+'-'+prefix

	first_line = True
	messages = []
	for line in message.split('\n'):
		if len(line) == 0:
			messages.append(line)
		elif first_line:
			messages.append('%'+prefix+' '+line)
			first_line = False
		else:
			messages.append('-'+prefix+' '+line)

	print '\n'.join(messages)

	stop = key.lower().find('stop') == 0

	if wseif == 'W':
		if stop: sys.exit(0)

	elif wseif == 'S':
		if stop: sys.exit(1)

	elif wseif == 'E':
		sys.exit(2)

	elif wseif == 'I':
		if stop: sys.exit(3)

	elif wseif == 'F':
		sys.exit(4)

	return
