#!/usr/bin/python

import os, os.path, sys, fnmatch, random, glob, signal
import shutil, time, socket, select, string, struct
from mrc_config import bbsname

bbsdir=os.getcwd()

# keep this
client_version="Mystic Relay Chat Client v1.0"
# Change this info
tempdir= "%s%stemp" % (bbsdir,os.sep)
datadir= "%s%sdata" % (bbsdir,os.sep)
mrcdir = "%s%smrc" % (datadir,os.sep)
chatdats = "%s%schat*.dat" % (datadir,os.sep)

## global vars
host = sys.argv[1]
port = int(sys.argv[2])
siteid=""

if(len(sys.argv) < 3) :
	print "Usage : mrc_client.py hostname port"
	sys.exit(1)

def loggit(loginfo):
  ltime=time.asctime(time.localtime(time.time()))
  print "%s : %s" % (ltime,loginfo.replace('\n',''))
  sys.stdout.flush()

def send2server(data):
	if data:
		try:
			mrcserver.send(data)
		except:
			loggit("Connection error")
			sys.exit()

def clean_files():
	mrcfiles = os.listdir( mrcdir )
	for file in mrcfiles:
		if fnmatch.fnmatch(file,'*.mrc'):
			mrcfile="%s%s%s" % (mrcdir,os.sep,file)
			os.remove(mrcfile)

def send_mrc():
	mrcfiles = os.listdir( mrcdir )
	for file in mrcfiles:
		if fnmatch.fnmatch(file,'*.mrc'):
			mrcfile="%s%s%s" % (mrcdir,os.sep,file)
			f = open(mrcfile,"r")
			fl=f.readline()
			mline=fl.split("~")
			fromuser=mline[0]
			message=mline[6]
			if message == "VERSION":
				deliver_mrc("CLIENT~~~%s~~~|07- %s~" % (fromuser,client_version))
			send2server(fl)
			f.close()
			os.remove(mrcfile)
	time.sleep(0.3)

def deliver_mrc( server_data ):
	r1=random.randint(1,99)
	r2=random.randint(1,99)
	r3=random.randint(1,99)
	r4=random.randint(1,99)
	r5=random.randint(1,99)
	filename = "%02d%02d%02d%02d%02d.mrc" % (r1,r2,r3,r4,r5 )

	dt1=server_data.split("~")
 	fromuser=dt1[0]
	fromsite=dt1[1]
 	fromroom=dt1[2]
 	totouser=dt1[3]
	totosite=dt1[4]
 	totoroom=dt1[5]
 	message=dt1[6]

	if message == "ping":
		send_im_alive()
	else:

		for f in glob.iglob(chatdats):
			if not 'chatroom' in f:
				chatfile="%s%schat" % (datadir,os.sep)
				xy=f.replace(chatfile,tempdir)
				xy=xy[:-4]
				inusefile="%s%stchat.inuse" % (xy,os.sep)
				if os.path.isfile(inusefile):
					mrcfile="%s%s%s" % (xy,os.sep,filename)
					openfile=open(mrcfile,"a")
					openfile.write(server_data)
					openfile.close()

def send_im_alive():
	data="CLIENT~%s~~SERVER~ALL~~IMALIVE:%s\n" % (bbsname,bbsname)
	send2server(data)

	

def mainproc():

	global loop
	global mrcserver 
	mrcserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	mrcserver.settimeout(2)

	loop=1
	readbuffer=""
	tdat=""

	#if os.sep == "/":
	#	mrcserver.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,1)
	#	mrcserver.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,1)
	#	mrcserver.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,3)
	#	mrcserver.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT,5)
	#else:
	#	mrcserver.ioctl(socket.SIO_KEEPALIVE_VALS,(1,10000,3000))

	try :
		mrcserver.connect((host,port))
		mrcserver.send("%s~" % bbsname)
		loggit("Connected to Mystic Relay Chat host %s" % host)
	except :
		loggit("Unable to connect to %s,%d" % (host,port))

	send_im_alive()
	time.sleep(0.25)
	while True:
		send_mrc()
		master_list = [mrcserver]
		rsock, wsock, esock = select.select(master_list, [], [],0)
		for sock in rsock:
			if sock == mrcserver:
				readbuffer=sock.recv(4096)
				if readbuffer:
					tdat=readbuffer.split(os.linesep)
					for data in tdat:
						if data:
							deliver_mrc(data)
				else:
					print "Lost connection to server.\n"
					sys.stdout.flush()
					mrcserver.close()
					sys.exit(1)
					
		time.sleep(0.25)

#		if loop % 1200 == 0:
#			send_im_alive()

		loop=loop+1
		if loop > 10000:
			loop=1

if __name__ == "__main__":
	signal.signal(signal.SIGINT, signal.SIG_DFL)
	try:
		mainproc()
	except KeyboardInterrupt:
		mrcserver.shutdown(2)
		mrcserver.close()