import telnetlib, re, datetime

config = {
	'ip': 		'192.168.1.1',
	'port': 	23,
	'user': 	'username',
	'password':	'password',
	'stateOK': 	['Up'],
	'logFile': 	'/home/username/zyxel-voip-status'
}



def logToFile( str ):
	datetimeStr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

	print '%s: %s' % (datetimeStr, str)

	if config['logFile'] != None:
		with open(config['logFile'],'a+') as f: f.write('%s: %s\n' % (datetimeStr, str))

	return



tn = telnetlib.Telnet(config['ip'], config['port'])

tn.read_until('Login:', 2)
tn.write(config['user'] + '\n')

tn.read_until('Password:', 2)
tn.write(config['password'] + '\n')

tn.read_until('>', 2)

tn.write('voice show\n')

stats = tn.read_until('>', 2)



pattern = re.compile(r'Account ([0-9]+):\r')
accounts = pattern.findall(stats)

pattern = re.compile(r'DisplayName\s+: (.+)\r')
displayNames = pattern.findall(stats)

pattern = re.compile(r'VoipServiceStatus\s+: (.+)\r')
status = pattern.findall(stats)


# some basic checking
if len(accounts) == 0 or len(displayNames) == 0 or len(status) == 0:
	print 'no accounts/names/status found'

if len(accounts) != len(displayNames) != len(status):
	print 'number of accounts/names/status not equal'


obj = map(lambda i, n, s: {'index': i, 'name': n, 'status': s in config['stateOK']}, accounts, displayNames, status)
inactiveAccounts = filter(lambda x: x['status'] != True, obj)



if len(inactiveAccounts) == 0:
	logToFile(str(len(obj)) + ' OK')
else:
	logToFile('Down: ' + ', '.join(map(lambda x: '%s (%s)' % (x['name'], x['status']), inactiveAccounts)))

	tn.write('voice reboot\n')


tn.write('exit\n')

tn.close