# -*- coding: utf-8 -*-
import os
import os.path
import socket
import commands
import sys
import gc
import time
import itertools
from itertools import chain
import re

import subprocess
from subprocess import Popen, PIPE

Sysname = os.environ.get("SYSNAME")
Tabfile = os.environ.get("SYSNAME") + 'tab'
Version = os.environ.get("KEIVER")
DiffDir = "/home/cms/diff"

pwdy = os.getcwd()

#---------------------------------------------------------------------
#awkの代わりの処理
#	password=`awk 'BEGIN {FS=";"} /^'#{base}';/ {print $5}' #{DiffDir}/cmssetq`
def awk(key,path,index):

	#p1 = re.compile("^"+key)
	p1 = re.compile(key)
	try:
		rfile = open(path)
	except IOError:
		return -1
	while True:
		line = rfile.readline()
		if not line:
			break
		if re.search(p1,line):
			obj = line.split(";")[index]
			rfile.close()
			return obj
	return ' '
	rfile.close()

#---------------------------------------------------------------------
#awkの代わりの処理
#	pfile=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $1}'`
def awk_fs(fs,str,index):

	try:
		obj = str.split(fs)[index]
	except IndexError:
		return ' '
	return obj

#---------------------------------------------------------------------
#grepの代わりの処理
#		target2=[i[7,len].sub(/\./,"_")]
#		check=`grep "lock" #{DiffDir}/lock/#{Sysname}/#{target2}/lkfile#{Version}`

def grep(key,fname,path,index):

	filename=fname
	p1 = re.compile(key)
	try:
		rfile = open(path)
	except IOError:
		return -1

	while True:
		line = rfile.readline()
		if not line:
			break
		if re.search(p1,line):
			obj = line.split(";")[index]
			rfile.close()
			return obj.rstrip()
	return ' '
	rfile.close()

#---------------------------------------------------------------------
#grepとTailとawkのパイプを実現(unget用)
#	op=`grep '#{Sysname};.*;#{i[7,len]};.*;GET' #{DiffDir}/log/getlog.#{Version}
#		| tail -1 | awk 'BEGIN {FS=";"}{print $3}'`
#
def greptail2(key,path,index):

	p2 = re.compile(key)
	try:
		rfile = open(path)
	except IOError:
		return -1
	i=0
	while True:
		line = rfile.readline()
		if not line:
			break
		#print line
		if re.search(p2,line):
			i = i + 1
	
	i = i - 1
	
	rfile.close()
	p2 = re.compile(key)
	rfile = open(path)
	j=0
	while True:
		line = rfile.readline()
		if not line:
			break
		if re.search(p2,line):
			check1 = line.split(';')[index]
			if j == i:
				rfile.close()
				return check1.rstrip()
			j = j + 1

	return ' '
	rfile.close()
	
#---------------------------------------------------------------------
#grepとTailとawkのパイプを実現
#	op=`grep '#{Sysname};.*;#{i[7,len]};' #{DiffDir}/log/getlog.#{Version}
#		| tail -1 | awk 'BEGIN {FS=";"}{print "[", $1,":" $2,$3,$4,$5"] to ",$6}'`
#
def greptail(key,path,index):

	p2 = re.compile(key)
	try:
		rfile = open(path)
	except IOError:
		return -1
	i=0
	while True:
		line = rfile.readline()
		if not line:
			break
		if re.search(p2,line):
			i = i + 1
	
	i = i - 1
	
	rfile.close()
	p2 = re.compile(key)
	rfile = open(path)
	j=0
	while True:
		line = rfile.readline()
		if not line:
			break
		if re.search(p2,line):
			check1 = line.split(";")[0]
			check2 = line.split(";")[1]
			check3 = line.split(";")[2]
			check4 = line.split(";")[3]
			check5 = line.split(";")[4]
			check6 = line.split(";")[5]
			if j == i:
				rfile.close()
				return check1.rstrip() + " " + check2.rstrip() + " " + check3.rstrip() + " " + check4.rstrip() + " " + check5.rstrip() + " to " + check6.rstrip()
			j = j + 1
	return ' '
	rfile.close()
	
#print grep('^lock','cms3-server.rb','/home/cms/diff/lock/test/cms3-server_rb/lkfile0',0)
	
#print greptail('^android;','/home/cms/diff/log/getlog.0',0)
	

host = "codoo2hk.corede.net"
port = 3388

base ='test'

sp = " "
s = socket.socket()
s.bind((host, port))
s.listen(1)
while 1:
	conn, addr = s.accept()  # クライアントの接続を待つ
	data = conn.recv(1024)  # クライアントからのデータを受信する
	#print "server: receive '%s'" % data.split()
	for i in data.split('\n'):
		#print i
		#length = i.len()
		if i == 'USER '+Sysname+'\r':
			#conn.send('+OK USER \r')
			conn.send('+OK USER' + '\r\n')
			#continue

			#シェル変数の$SYSNAMEをユーザIDとしてパスワードを調べる
			password = awk('^'+Sysname+';+','/home/cms/diff/cmssetq',4)

		if i == 'PASS ' + password + '\r':
			conn.send('+OK PASS' + '\r\n')

#--------------------------------------------------------------------------------------
		#LISTのための処理
		if i[0:6] == 'STAT 0':
			conn.send('+NT STAT 0' + ' ' + pwdy + ' ' + '\r\n')

#--------------------------------------------------------------------------------------
		#NEWFILEのための処理
		if i == 'STAT ' + '1 ' + '\r':
			if (os.path.exists(i[7:].rstrip()) == True):
				target=i
				sendstr = '+OK STAT 1 ' + i + '\r\n'
				conn.send(sendstr)
			else:
				#conn.send('+NG STAT 1 ' + '\r\n')
				sendstr = '+NG STAT 1 ' +'\r\n'
				conn.send(sendstr)

#--------------------------------------------------------------------------------------
		#WHOのための処理
		if i[0:6] == 'STAT 2':
			target2 = i[7:].replace('.','_')
			#リビジョンファイルがロックされているかどうか
			#check=`grep "lock" #{DiffDir}/lock/#{Sysname}/#{target2}/lkfile#{Version}`
			check= grep('^lock',target2,'/home/cms/diff/lock/'+Sysname+'/'+target2.rstrip()+'/lkfile'+Version,0)
			if check == -1:
				continue
			#もしロックされている場合はその情報をGETLOGファイルから読み取り報告する
			if check == 'lock':
				#op=`grep '#{Sysname};.*;#{i[7,len]};' #{DiffDir}/log/getlog.#{Version} | tail -1 | awk 'BEGIN {FS=";"}{print "[", $1,":" $2,$3,$4,$5"] to ",$6}'`
				op = greptail(Sysname+';.*;'+i[7:].rstrip()+';','/home/cms/diff/log/getlog.'+Version,0)
				#op = greptail('test;.*;test02.java;','/home/cms/diff/log/getlog.'+Version,0)
				#print op
				if op == None:
					conn.send('-OK STAT 2 ' + i[7:].rstrip() + ' GET -> ' + '\r\n')
				else:
					conn.send('-OK STAT 2 ' + i[7:].rstrip() + ' GET -> ' + op.rstrip() +'\r\n')
					#conn.send('-OK STAT 2 ' + i[7:].rstrip() + ' GET -> ' + op)
			else:
				#conn.send('-NG STAT 2 ' + '\r\n')
				#conn.send('-NT STAT 2 ' + i[7:].rstrip() + ' Available GET ' + '\r\n')
				conn.send('-NT STAT 2 ' + i[7:].rstrip() + ' Available GET ')

#--------------------------------------------------------------------------------------
		if i[0:6] == "STAT 3":
			#if File.exist?(i[7,len]) == true
			if (os.path.exists(i[7:].rstrip()) == True):
				target=i[7:]
				conn.send('+OK STAT 3 ' + i[7:].rstrip() + '\r\n')
			else:
				conn.send('+NG STAT 3' + '\r\n')

#--------------------------------------------------------------------------------------
		#GETのための処理
		if i[0:6] == "STAT 4":
			#target4=[i[7,len].sub(/\./,"_")]
			target4 = i[7:].replace('.','_')
			#リビジョンファイルがロックされているかどうか
			#check=`grep "lock" #{DiffDir}/lock/#{Sysname}/#{target4}/lkfile#{Version}`
			check= grep('^lock',target4,'/home/cms/diff/lock/'+Sysname+'/'+target4.rstrip()+'/lkfile'+Version,0)
			#もしロックされている場合はその情報をGETLOGファイルから読み取り報告する
			if check == "lock" :
				#op=`grep '#{Sysname};.*;#{i[7,len]};' #{DiffDir}/log/getlog.#{Version} | tail -1 | awk 'BEGIN {FS=";"}{print "[", $1,":" $2,$3,$4,$5"] to ",$6}'`
				op = greptail(Sysname+';.*;'+i[7:].rstrip()+';','/home/cms/diff/log/getlog.'+Version,0)
				if op == None:
					conn.send('+NT STAT 4 ' + i[7:].rstrip() + ' GET -> ' + op + '\r\n')
				else:
					conn.send('+NT STAT 4 ' + i[7:].rstrip() + ' GET -> ' + op)
			else:
				conn.send('+OK STAT 4 ' + i[7:].rstrip() + ' Available GET ' + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでLIST（ファイルのリスト表示)は行わない
		if i[0:6] == 'LIST 0':
			conn.send('+OK LIST 0' + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでLIST（ファイルのリスト表示)を行う
		if i[0:6] == 'LIST 1':
			if (os.path.exists(Tabfile) == True):
				ret = commands.getoutput('cp -p testtab /home/cms/diff/tabs')

			sendstr = '+OK LIST 1 '
			rfile = open('/home/cms/diff/tabs/' + Tabfile)
			while True:
				line = rfile.readline()
				if not line:
					break
				sendstr =  sendstr + line.rstrip() + ' '

			#print sendstr

			sendstr =  sendstr + '\r\n'
			conn.send(sendstr)

			rfile.close()

#--------------------------------------------------------------------------------------
		#ここでリビジョンのLIST（ファイルのリビジョンリスト表示)を行う
		if i[0:6] == 'LIST 2':
			#list2 = ['+OK LIST 2'] 
			list2 = '+OK LIST 2'
			revDir=i[7:].replace('.','_')
			rfile = open('/home/cms/diff/lock/'+Sysname+'/'+revDir.rstrip()+'/verfile.'+Version)
			while True:
				line = rfile.readline()
				if not line:
					break
				list2 = list2 + line.rstrip() + ' '
			rfile.close()
			#print list2
			conn.send(list2)
			conn.send('\r\n')
#--------------------------------------------------------------------------------------
		#ここでPUTは行わない
		if i[0:6] == 'STOR 0':
			conn.send('+OK STOR 0' + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでPUTを実行する
		if i[0:6] == 'STOR 1':
			#pfile=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $1}'`
			pfile = awk_fs(':',i[6:].rstrip(),0)
			#p=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $2}'`
			p = awk_fs(':',i[6:].rstrip(),2)
			memo = p.rstrip()
			param = pfile + ' ' + Sysname + ' ' + Version + ' ' + memo
			#print 'DEBUG:' + param
			#check=`cms3-put.ksh #{param}`
			try:
				check = subprocess.check_output('cms3-put.ksh' + ' ' + param, shell=True)
			except OSError:
				print 'error'
				continue
			if check.rstrip() == '-OK PUT':
				conn.send('+OK STOR 1' + '\r\n')
			else:
				#conn.send('+NT STOR 1' + check.rstrip() + '\r\n')
				conn.send('+NT STOR 1' + check.rstrip())

#--------------------------------------------------------------------------------------
		#ここでNEWFILEを実行する
		if i[0:6] == 'STOR 2':
			#pfile=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $1}'`
			pfile = awk_fs(':',i[6:].rstrip(),0)
			#p=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $2}'`
			p = awk_fs(':',i[6:].rstrip(),2)
			#memo = p.chomp
			memo = p.rstrip()
			#param = pfile.chomp + " " + base + " " + "#{Version}" + " " + "#{memo}"
			param = pfile.rstrip() + ' ' + Sysname + ' ' + Version + ' ' + memo
			#puts "DEBUG:" + param
			#check=`cms3-newfile.ksh #{param}`
			try:
				check = subprocess.check_output('cms3-newfile.ksh' + ' ' + param, shell=True)
			except OSError:
				print 'error'
			if check.rstrip() == '-OK NEW':
				conn.send('+OK STOR 2' + '\r\n')
			else:
				conn.send('+NT STOR 2' + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでGETは行わない
		if i[0:6] == 'RETR 0':
			conn.send('+OK RETR 0' + '\r\n')
#--------------------------------------------------------------------------------------
		#ここでGETを実行する
		if i[0:6] == 'RETR 1':
			#param = i[6,len] + " " + base + " " + "#{Version}"
			param = i[6:].rstrip() + ' ' + Sysname + ' ' + Version
			#`cms3-get.ksh #{param}`
			#check=`cms3-get.ksh #{param}`
			try:
				check = subprocess.check_output('cms3-get.ksh' + ' ' + param, shell=True)
			except OSError:
				print 'error'
			if check.rstrip() == '-OK GET':
				conn.send('+OK RETR 1' + check.rstrip() + '\r\n')
			else:
				conn.send('+NT RETR 1' + check.rstrip() + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでUNGETを実行する
		if i[0:6] == 'RETR 2':
			#op=`grep '#{Sysname};.*;#{i[7,len]};.*;GET' #{DiffDir}/log/getlog.#{Version} | tail -1 | awk 'BEGIN {FS=";"}{print $3}'`
			op= greptail2(Sysname+';.*;'+i[7:].rstrip()+';.*;GET','/home/cms/diff/log/getlog.'+Version,2)
			#puts "base= " + base
			#print "op= " + op
			if op == Sysname:
				#param = i[6,len] + " " + base + " " + "#{Version}"
				param = i[6:].rstrip() + ' ' + Sysname + ' ' + Version
				#print 'param= ' + param
				#check=`cms3-unget.ksh #{param}`
				try:
					check = subprocess.check_output('cms3-unget.ksh' + ' ' + param, shell=True)
				except OSError:
					print 'error'
				if check.rstrip() == '-OK UNG':
					conn.send('+OK RETR 2 ' + check.rstrip() + '\r\n')
				else:
					conn.send('+NT RETR 2 ' + check.rstrip() + '\r\n')
			else:
				conn.send('+NT RETR 2 ' + op + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでVGETを実行する
		if i[0:6] == 'RETR 3':
			#rfile=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $1}'`
			rfile = awk_fs(':',i[6:].rstrip(),0)
			#r=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $2}' | awk 'BEGIN {FS="."}{print $2}'`
			r = awk_fs(':',i[6:].rstrip(),1)
			r2 = awk_fs('.',r,1)
			revision = r2.rstrip()
			#param = rfile.chomp + " " + base + " " + "#{Version}" + " " + "#{revision}"
			param = rfile.rstrip() + ' ' + Sysname + ' ' + Version + ' ' + revision
			#print param
			#check=`cms3-vget.ksh #{param}`
			try:
				check = subprocess.check_output('cms3-vget.ksh' + ' ' + param, shell=True)
			except OSError:
				print 'error'
			if check.rstrip() == '-OK VGT':
				conn.send('+OK RETR 3' + check.rstrip() + '\r\n')
			else:
				conn.send('+NT RETR 3' + check.rstrip() + '\r\n')

#--------------------------------------------------------------------------------------
		#ここでUNVGETを実行する
		if i[0:6] == 'RETR 4':
			#rfile=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $1}'`
			rfile = awk_fs(':',i[6:].rstrip(),0)
			#r=`echo #{i[6,len]} | awk 'BEGIN {FS=":"}{print $2}' | awk 'BEGIN {FS="."}{print $2}'`
			r = awk_fs(':',i[6:].rstrip(),1)
			r2 = awk_fs(':',r,1)
			revision = r2.rstrip()
			#param = rfile.chomp + " " + base + " " + "#{Version}" + " " + "#{revision}"
			param = rfile.rstrip() + ' ' + Sysname + ' ' + Version + ' ' + revision
			#check=`cms3-unvget.ksh #{param}`
			try:
				check = subprocess.check_output('cms3-unvget.ksh' + ' ' + param, shell=True)
			except OSError:
				print 'error'
			if check.rstrip() == '-OK UNV':
				conn.send('+OK RETR 4 ' + check.rstrip() + '\r\n')
			else:
				conn.send('+NT RETR 4 ' + check.rstrip() + '\r\n')

#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
		if  (i == 'QUIT \r'):
			conn.send('+OK QUIT   \r\n')  # クライアントにデータを送信する
			conn.close()
			break
s.close()

