#!/usr/bin/env python

import sys, os, cgi, time, types, re
from cgitools import *
#cgi_token = "Content-type:text/html\n\n"
#error_info = []

data_set = {'user_id':{'required':1, 'to_upper':0}, 'password':{'required':1, 'to_decrypt':True, 'to_encrypt':'md5'}, 'password_confirm':{'required':1, 'to_decrypt':True, 'to_encrypt':'md5'}, 'first_name':{'required':1}, 'last_name':{'required':1}, 'company':{}, 'street':{}, 'city':{}, 'state':{}, 'zip':{}, 'country':{}, 'phone':{}, 'email':{'required':1}} # the default value is {'required':0, 'type':'string', 'to_encrypt':'', 'to_upper':0}
data_to_be_save = {'user_id':'user_name', 'password':'user_passwd', 'first_name':'first_name', 'last_name':'last_name', 'company':'company', 'street':'street', 'city':'city', 'state':'state', 'zip':'zip', 'country':'country', 'phone':'phone', 'email':'email'}

def produceStr(v, sep='"'):
	if type(v) is types.StringType: return '%s%s%s' % (sep, v.replace('\\','\\\\').replace('"','\\"'), sep) #sep + v + sep
	return repr(v)

my_vars = {'ui_logon':script_path_url+'/ui'}


# read data from cgi form.
form_data = {}
form = cgi.FieldStorage()

rsa_key = ''

t_now = getSec(n=2)

for k,v in data_set.items():
	if form.has_key(k):
		fv = form.getvalue(k)
		if not v.get('to_decrypt', False): fv = fv.strip()
		if not fv:
			if v.get('required', 0): error_info.append("Error: required items (%s) didn't supplied!" % k)
			continue
		if v.get('type', 'string') != 'string': pass # need to some transformation here if there is any data other than string to be used.
		if v.get('to_upper',0): fv = fv.upper()
		
		if v.get('to_decrypt', False):
			if rsa_key == '': rsa_key = getRSAkeys()
			if rsa_key: 
				fv = rsaStr(fv, rsa_key[1], rsa_key[2], True, 8, True)
				srv_tag, fv = fv[-4:], fv[:-4]
				if not srv_tag: exitWithInfo('Error in data that need encryption!')
				t_diff = t_now - Str2Num(srv_tag, hex_str=True)
				if t_diff<0 or t_diff>15: exitWithInfo('Time out error!')

		if v.get('to_encrypt', '') == 'md5': fv = myMD5(fv)
		form_data[k] = fv
	elif v.get('required', 0):
		error_info.append("Error: required items (%s) didn't supplied!" % k)
		#break

# check user_id
user_id = form_data.get('user_id', '')
if not re.match(r'^[a-zA-Z0-9_]+$', form_data.get('user_id', 'a')): error_info.append('Error: Invalid characters in the user ID!') 
elif user_id.lower() in RESERVED_USERNAME: error_info.append('Error: This ID was RESERVED!')


# check password
if form_data.has_key('password') and form_data.has_key('password_confirm') and form_data['password'] != form_data['password_confirm']:
	error_info.appdne("Error: passwords doesn't match!")

#check email
if not re.match(r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+', form_data.get('email', 'a@a.a')): error_info.append('Error: Invalid email address!')

# check user_name in db

connection, cur = getConnectionCursor()
 
cur.execute('LOCK TABLES users WRITE, evlog WRITE')
if user_id: #form_data.get('user_id', ''):
	sql_statement = 'SELECT user_name FROM users WHERE user_name="%s"' % user_id #form_data['user_id'] 
	n = cur.execute(sql_statement)
	if n: error_info.append("Error: user Id (%s) is already in use!" % user_id) #form_data['user_id'])
	#result_set = cur.fetchall()

if error_info: # exit
	cur.execute('UNLOCK TABLES')
	connection.close()
	exitWithInfo()
else:	#update db
	vars_available = filter(data_to_be_save.has_key, form_data.keys())
	values_available = map(form_data.get, vars_available)
	fields_related = map(data_to_be_save.get, vars_available)
	fields_related.append('register_time')
	fields_str = ', '.join(fields_related)
	#values_str = repr(tuple(values_available))[1:-1]
	values_str = ", ".join(map(produceStr, values_available))
	date_time = time.strftime(', "%Y-%m-%d %H:%M:%S"', time.gmtime())
	sql_statement = ("INSERT INTO users (%s) VALUES (" % fields_str) + values_str + date_time + ')'
	
	#exitWithInfo(values_str+'<p>'+sql_statement)

	#lg = open('logs.txt', 'wt')
	#lg.write(sql_statement)
	#lg.close()

	n = cur.execute(sql_statement) 
	saveEvent(ev_time=None, user_id=user_id, ev_catcode="register", ev_valcode=None, ev_valstr=None, cur=cur)
	if not n:# check if it is successful or not
		error_info.append('Error: failed to update databases. The server faces problem at this moment. Please try later.')
	elif os.name != 'posix': # should be windows
		sql_statement = 'UPDATE users SET act_state=1 WHERE user_name="%s"' % user_id
		cur.execute(sql_statement)
		if cur.rowcount >= 1:
			print cgi_token
			print "Your account was activated."
			#print "<p>click <a href='%s'>Here</a> to logon." % (script_path_url+'/ui')
			print "<p>click <a href='%s'>Here</a> to logon." % (base_dir_url)


cur.execute('UNLOCK TABLES')
connection.commit()
connection.close()

if error_info: exitWithInfo()
elif os.name != 'posix': 
	exitWithInfo(e_info="Congratulation! %s, your account was activated.<p>click <a href='%s'>Here</a> to logon." % (use_id, base_dir_url))

# send confirm email:
msg = '''To: %s
From: %s
Subject: Confirm registration on WebArray/WebArrayDB

Dear %s:

Please confirm your registration as %s on WebArray/WebArrayDB - click the following URL or copy it to a browser's address bar.

%s

Thanks for your interest in WebArray/WebArrayDB.

- WebArray/WebArrayDB
'''
#msg = "To: %s\nFrom: WebArray at SKCC\nSubject: Confirm registration\n\nDear %s:\n\nPlease confirm your registration - by click the following URL or copy it to a browse's address bar.\n\n%s\n\nThanks for you interest in our analysis system.\n\n- webarray\n"

from tools import encodeStr, email_admin
thd = 'http://%s%s/confirm/%s' % (http_host, script_path_url, encodeStr(form_data['user_id']))
#thd = 'http://'+http_host+'/'+script_path_url+'/confirm/'+encodeStr(form_data['user_id'])
msg = msg % (form_data['email'], email_admin, form_data['first_name'], user_id, thd)
MAIL = '/usr/sbin/sendmail'
p = os.popen('%s -f %s -t' % (MAIL, email_admin), 'w')
p.write(msg)
exitcode = p.close()

print cgi_token

if exitcode != 0:
	print "An email was sent to %s. Please check it to confirm your registration as %s. In case that you do not receive the confirmation email in ONE hour, please contact with the <a href=mailto:%s>administrator</a>." % (form_data['email'], form_data['user_id'], email_admin)
	print "<p>click <a href='%s'>Here</A> TO Logon." % my_vars['ui_logon']
else:
	print '<p> Exit code ', exitcode, '<br>'

#print "click <a href='ui/logon'>Here</a> to logon."
#from

#print cgi.print_environ() 

