#!/usr/bin/env python

################################################################################
#
# c01N.py : python script that set your PS1 as a c01N c01N prompt 
# Copyright (C) 2003  Brice Carpentier
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
################################################################################

import os, sys, color, time, struct, termios, fcntl, socket, sre

confdir = os.environ.get('HOME') + os.sep + '.c01N'
fstate = confdir + os.sep + 'state'

def getStringLenWOANSIEscapingSequence(text):
	"""returns texts's length, w/o all ANSI escaping sequence"""

	# checks argument validity
	assert isinstance(text, str), 'text should be a string'

	#pattern that matches an ANSI escaping sequence
	return(len(sre.sub("\\\\\[\\x1b.*?m\\\\\]", '', text)))
	

def getTermWidth():
	"""returns ther terminal's width"""
	
	height, width = struct.unpack(
			'hhhh', fcntl.ioctl(0, termios.TIOCGWINSZ ,"\000"*8))[0:2]
	return width


def c01n(state = 1):
	"""
	prints the c01n prompt in the current state:
	c01n(1) = \_o<
	c01n(2) = \_o=
	"""
	# checks for argument's validity
	assert isinstance(state, int), 'state should be an int'
	
	corps = color.green("\_") + color.red("o")
	
	if state <= 1:
		return corps + color.yellow('<')
	else:
		return corps + color.yellow('=')
	

if __name__ == "__main__":
	
	# checks for configuration directory existance
	if not(os.path.exists(confdir)):
		os.mkdir(confdir, 0700)
	
	assert not(os.path.isfile(confdir)), "~/.c01N must be a directory"
	
	if not(os.path.isfile(fstate)):
		ligne = '2'
	else:
		f = file(fstate, 'r')
		
		try:
			ligne = f.readline()
		finally:
			f.close()
			del(f)
	
	
	f = file(fstate, 'w')

	try:
		if ligne == '2':
			state = 2
			f.write('1')
		else:
			state = 1
			f.write('2')
	finally:
		f.close()
		del(f)


	# gets the username
	# if it's root, let's highlight it
	user = os.environ.get('USER')
	
	if user == 'root':
		user = color.bold(color.red(user))
	
	hostname = socket.gethostname()
	cwd = os.getcwd()

	if cwd == os.environ.get('HOME'):
		cwd = '~'
	
	lcltm = time.localtime()
#	dateandtime = str(lcltm[1]) + '/' + str(lcltm[2]) + '/' + \
#                      str(lcltm[0]) + ' ' + str(lcltm[3]) + ':' + \
#                      str(lcltm[4]) + ':' + str(lcltm[5])
		      
	dateandtime = "%02d/%02d/%04d %02d:%02d:%02d" % \
			(lcltm[2], lcltm[1], lcltm[0], \
			lcltm[3], lcltm[4], lcltm[5])
		      
	leftheader = color.resetColor() + color.teal('[ ') + \
	user + color.teal(' ]=[ ') + \
	hostname + color.teal(' ]=--')

	rightheader = color.resetColor() + color.teal('--=[ ') + \
	dateandtime + color.teal(' ]')
	
	footer = color.resetColor() + color.teal('[ ') + \
		 color.resetColor() + cwd + color.teal(' ]-[ ') + \
		 color.resetColor() + c01n(state) + color.teal(' ]')
	
	print leftheader + \
	      ' ' * (\
	      getTermWidth() - \
	      getStringLenWOANSIEscapingSequence(leftheader) - \
	      getStringLenWOANSIEscapingSequence(rightheader)) + \
	      rightheader + "\n" + footer + " "

