#!/usr/bin/env python

import os
import sys
import string

import _mysql
import getpass
import time, random
from types import *

print 'Content-Type: text/html'
print
print '<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">'


"""update agriT set subject=replace(subject,'\\','') function definition """
def file_mod(a) :
	if string.strip(a) == 'None' :
		return ""
	if string.strip(a) == 'NULL' :
		return ""
	if string.strip(a) == '' :
		return ""
	b = string.split(a, '/')
	file = "data/"+ b[3]
	return file

def document_root() :
	a = os.getcwd()
	b = string.split(a, '/')
	file = "/"+ b[1] +"/"+ b[2]
	return file

def get_dbinfo():
	query = os.environ.get("QUERY_STRING")
	tmp = string.split(query, "&")

	t = {'host':'', 'user':'', 'passwd':'', 'dbname':'', 'tbname':''}
	t['host'] = tmp[0]
	t['user'] = tmp[1]
	t['dbname'] = tmp[2]
	t['passwd'] = tmp[3]
	t['tbname'] = tmp[4]

	return t

def test_connect(t):
	isOK = True
	host = t['host']
	user = t['user']
	passwd = t['passwd']
	dbname = t['dbname']
	
	try :
		db = _mysql.connect(host, user, passwd, dbname)
		db.close()
	except Exception :
		isOK = False
	return isOK

def replace_escape(str) :
	return string.replace(str, "\'", "\\'")

def str_in(t) :
	return replace_escape(str(t))

""" main() """

"""
	검사
	1. bn 충돌여부 검사 
	2. 충돌의 경우 다른 것으로 . .....
"""
info = get_dbinfo()

try:
	test_connect(info)
except:
	print "죄송합니다. 입력하신 정보가 잘못 되었습니다 . 정확히 다시 입력하십시오."
	sys.exit(0)

host = info['host']
user = info['user']
passwd =info['passwd']
dbname = info['dbname']
alias = info['tbname']

zalias = alias
ztb = "zetyx_board_"+alias
ztb_memo = "zetyx_board_comment_"+alias
ztb_cate = "zetyx_board_category_"+alias

alias_pro = []
"""
alias_asa = []
bn_asa = []
mm_asa = []
"""
db = _mysql.connect(host, user, passwd, dbname)

"""
sql = "select * from zetyx_admin_table where name='"+ zalias +"'"
db.query(sql)
result = db.store_result()
zcfg = result.fetch_row(0)
"""

"""
sql = "select alias, boardName, memoName from boardAdmin order by alias"
for i in range(0, len(row)) :
	alias_asa.append(row[i][0])
	bn_asa.append(row[i][1])
	mm_asa.append(row[i][2])
"""

"""
	데이터 옮겨오기
	1. 게시판생성
	2. 본글
	3. 댓글
	4. 알림글
	5. 관리자 암호
"""
alias = string.replace(alias,"-","_")

sql = "select alias from ASADAL_BOARD_ADMIN order by alias"
db.query(sql)
result = db.store_result()
row = result.fetch_row(0)
for j in range(0, len(row)) :
	alias_pro.append(row[j][0])

if alias in alias_pro :
	dup_cnt = 2
	alias_bak = alias
	while True :
		alias = alias_bak + str(dup_cnt)
		if alias in alias_pro :
			dup_cnt = dup_cnt + 1
			continue
		else :
			break

# 게시판 생성
sql = "create table ASADAL_BOARD_"+ alias +" ( pkid int(11) NOT NULL auto_increment, fmlid int(5) NOT NULL default '0',  parent varchar(50) NOT NULL default '', parentcp varchar(50) NOT NULL default '',  writer varchar(100) NOT NULL default '',  member_num varchar(32) default '0',  subject varchar(100) NOT NULL default '',  date date NOT NULL default '0000-00-00',  count int(5) NOT NULL default '0',  reCount int(5) NOT NULL default '0',  contents text,  email varchar(50) default NULL,  pw varchar(100) default NULL,  fileFlag int(1) default NULL,  fileHost varchar(50) default '',  filePath varchar(100) default NULL,  level int(2) default NULL,  ip varchar(50) NOT NULL default '',  visible int(1) NOT NULL default '0',  pageUID varchar(100) NOT NULL default '',  time varchar(10) NOT NULL default '',  gmt varchar(50) NOT NULL default '',  asadal varchar(100) default NULL,  whisper int(1) NOT NULL default '0',  userHtml tinyint(1) NOT NULL default '0',  category int(11) NOT NULL default '0',  asadal2 varchar(100) default NULL,  asadal3 varchar(100) default NULL,  PRIMARY KEY  (pkid),  UNIQUE KEY pageUID (pageUID),  KEY count (count),  KEY reCount (reCount),  KEY writer (writer),  KEY subject (subject),  KEY pkid (pkid),  KEY parent (parent),  KEY parentcp (parentcp),  KEY pageUID_2 (pageUID),  KEY gmt (gmt),  KEY ip (ip),  KEY fmlid (fmlid),  KEY category (category))"
db.query(sql)
sql = "create table ASADAL_BOARD_MEMO_"+ alias +" (pk int(11) NOT NULL auto_increment, fk varchar(50) default '', pw varchar(100) NOT NULL default '', writer varchar(50) NOT NULL default '', member_num varchar(32) default NULL, date datetime NOT NULL default '0000-00-00 00:00:00', memo varchar(255) NOT NULL default '', code varchar(50) NOT NULL default '', marks char(2) default '', recom char(2) default '', ip varchar(50) NOT NULL default '', id varchar(20) NOT NULL default '',  PRIMARY KEY  (pk),  KEY memo_fk (fk),  KEY memo_code (code))"
db.query(sql)
sql = "insert into ASADAL_AUTH_MENU(level, parent, child, title, name, info, root_seq, auto, link, yes_use, yes_show, ranking, img, img_over) values (2,5,0,'"+ alias +"','기본관리자','"+ alias +"',5,1,'',1,1,99,NULL,NULL)"
db.query(sql)
sql = "select max(seq) as seq from ASADAL_AUTH_MENU"
db.query(sql)
result = db.store_result()
row = result.fetch_row(0)
seq = row[0][0]
sql = "insert into ASADAL_BOARD_ADMIN(boardName, alias, auth_seq, boardTitle, memoName, backcolor, useSkin, settingDate, modifyDate, control, control_auth, boardPos ) values ('ASADAL_BOARD_"+ alias +"','"+ alias +"','"+ seq +"','"+ alias +"','ASADAL_BOARD_MEMO_"+ alias +"','',1,now(),now(),'||','||','')"
db.query(sql)

# 디렉토리생성
os.system("mkdir "+ document_root() + "/asapro/board/bn/" + alias)
os.system("cp "+ document_root() + "/asapro/board/bn/text.php "+ document_root() + "/asapro/board/bn/"+alias)
os.system("cp "+ document_root() + "/asapro/board/bn/board/env2.ini "+ document_root() + "/asapro/board/bn/"+alias)
os.system("touch "+ document_root() + "/asapro/board/bn/"+ alias + "/begin.htm")
os.system("touch "+ document_root() + "/asapro/board/bn/"+ alias + "/end.htm")
os.system("touch "+ document_root() + "/asapro/board/data/count"+ alias +".txt")
os.system("chmod 777 "+ document_root() + "/asapro/board/data/count"+ alias +".txt")
os.system("chmod 777 "+ document_root() + "/asapro/board/bn/" + alias)
os.system("chmod 777 "+ document_root() + "/asapro/board/bn/" + alias + "/text.php")
os.system("chmod 777 "+ document_root() + "/asapro/board/bn/"+ alias +"/env2.ini")


# 기본환경설정 적용하기
sql = "insert into ASADAL_BOARD_CFG(boardName, memoName, rowsPerAPage,nPageNvgt,fieldbgColorOfList,fieldTextColorOfList,fieldTextFontSizeOfList,fieldTextFontFmlOfList,textbgColorOfList,textColorOfList,textFontSizeOfList,textFontFmlOfList,cellpaddingOfList,borderColorOfList,heightOfList,isReply,isHOTICON,cdtOfHOTICON,isNEWICON,isFILEICON,isLineNumSorting,isWriter,isDate,isCounter,isRecommend,isNO,fieldbgColorOfWrite,fieldTextColorOfWrite,fieldTextFontSizeOfWrite,fieldTextFontFmlOfWrite,textbgColorOfWrite,textColorOfWrite,textFontSizeOfWrite,textFontFmlOfWrite,cellpaddingOfWrite,borderColorOfWrite,heightOfWrite,isHTML,isEMAIL,isFileUpLoad,fileUpLoadSize,fieldbgColorOfRead,fieldTextColorOfRead,fieldTextFontSizeOfRead,fieldTextFontFmlOfRead,textColorOfRead,textbgColorOfRead,textFontSizeOfRead,textFontFmlOfRead,cellpaddingOfRead,borderColorOfRead,heightOfRead,isRelation,borderColorOfMEMO,bgColorOfMEMO,rstIP,rstWords,header,footer,email,ip,words,emailHeader,allPageWidth,isListAll,textIndent,skinName,isBegin,isEnd,isPub,pubName,nPubs,isPubBold,whereSkin,mouseOverColor,isShowBgImage,asadal,asadalName,isAsadal,antiSpam,heightOfField,dfFontColor,dfFontSize,dfFontFamily,dfFontHeight,isCheckview,tableType,isPw_r,fileUpLoadCnt,isFileInfo,commName,isStop,newIcon,hotIcon,whisperIcon,cutIcon,ip_hide,writer_edit_not,writerType,whisper_hide,asaedit_hide,search_hide,writebox_dtext,allcount_hide,count_hide,downFiles,adminimg_hide,boardPos,isCategory,categorySelectbox,categoryPos,loginType,loginPage,sorting,sort_order,new_date,isAsadal2,asadalName2,isAsadal3,asadalName3,adminPass,tableAlign,is_autoskin) values ('ASADAL_BOARD_"+ alias +"','ASADAL_BOARD_MEMO_"+ alias +"',30,10,'#E0EAFF','#1E3565','9','gulim','#FFFFFF','#545555','9','gulim',3,'#B9CCF3',20,1,1,100,1,0,0,1,1,1,0,1,'#E0EAFF','#1E3565','9','gulim','#FFFFFF','#545555','9','gulim',3,'#B9CCF3',20,1,0,0,1,'#E0EAFF','#1E3565','9','gulim','#545555','#FFFFFF','9','gulim',3,'#B9CCF3',20,1,'','',0,0,'','','','','','','100%',1,0,'hEmbossBlue',1,1,1,'공지',1,1,0,'#FFFFFF',1,NULL,'',0,0,NULL,'#000000',8,'굴림',20,0,2,0,3,0,'',0,'','','','',1,1,1,0,0,1,'',1,1,'txt/gif/doc/hwp/jpg/ppt/pdf/htm/html/php/inc',1,'',0,1,1,2,1,'number','desc',1,0,'',0,'','8af640b8bcd775b096df1e1fb64b61fc','0','1')"
db.query(sql)

# 분류
sql = "select no, name from " + ztb_cate
db.query(sql)
result = db.store_result()
row = result.fetch_row(0)
if len(row) != 0 :
	zcateArr = {}
	for t in range(0, len(row)) :
		sql = "select max(seq) from ASADAL_BOARD_CATEGORY"
		db.query(sql)
		result = db.store_result()
		maxseq = result.fetch_row(0)
		if maxseq[0][0] > 0 :
			seq = int(maxseq[0][0]) + 1
		else:
			seq = 1

		zcate = row[t][0]
		zcateArr[zcate] = seq

		sql = "insert into ASADAL_BOARD_CATEGORY(seq, boardName, name, num) values ('"+ str_in(seq) +"','"+ str_in(alias) +"','"+ str_in(row[t][1]) +"', '"+ str_in(row[t][0]) +"')"
		db.query(sql)


# 본글
sql = "select * from " + ztb + " where headnum > -2000000000 order by headnum DESC, arrangenum ASC"
db.query(sql)
result = db.store_result()
row = result.fetch_row(0)

if len(row) == 0 :	# 글이 없으면 끝낸다.
	print "	<script>alert('제로보드 "+ zalias +"게시판을 아사프로 "+ alias +"게시판으로 옮겼습니다.')</script>"
	sys.exit(0)

# 게시물 변환 부분
fmlid = 0
uidRange = range(1,10000)
for temp in range(0, len(row)) :
	parentArr = {}
	parentArr[0] = "A"

	if int(row[temp][3]) > 0 :
		depth = int(row[temp][4])+1
		for i in range(depth) :
			if i < before_parentLen:
				if i == int(row[temp][4]) :
					parentArr[i] = chr(ord(before_parentArr[i])+1)
				else:
					parentArr[i] = before_parentArr[i]
			else:
				parentArr[i] = "A"
	else:
		fmlid = fmlid + 1

	before_parentArr = parentArr
	before_parentLen = len(parentArr)

	parent = ""
	for i in range(0, len(parentArr)) :
		parent = parent + parentArr[i]


	zdate = time.strftime("%Y-%m-%d", time.localtime(int(row[temp][30])))
	ztime = time.strftime("%H:%M:%S", time.localtime(int(row[temp][30])))

	zcatenum = row[temp][20]
	cate = zcateArr[zcatenum]

	if row[temp][24] or row[temp][25]:
		fileFlag = 1
	else:
		fileFlag = ""

	uid1 = time.strftime("%Y%m%d%H%M%S", time.localtime(int(row[temp][30])))
	uid2 = random.choice(uidRange)
	uid = str(uid1)+str(uid2)

	sql = "insert into ASADAL_BOARD_"+ alias +" (pkid, fmlid, parent, parentcp, writer, member_num, subject, date, count, reCount, contents, email, pw, fileFlag, filePath, level, ip, visible, pageUID, time, gmt, whisper, userHtml, category) values ('"+ str_in(row[temp][0]) +"', '"+ str_in(fmlid) +"', '"+ str_in(parent) +"', '"+ str_in(parent) +"', '"+ str_in(row[temp][14]) +"', '', '"+ str_in(row[temp][17]) +"', '"+ str_in(zdate) +"', '"+ str_in(row[temp][31]) +"', '"+ str_in(row[temp][32]) +"', '"+ str_in(row[temp][11]) +"', '"+ str_in(row[temp][16]) +"', '"+ str_in(row[temp][13]) +"', '"+ str_in(fileFlag) +"', '', '', '"+ str_in(row[temp][12]) +"', '1', '"+ str_in(uid) +"', '"+ str_in(ztime) +"', '"+ str_in(row[temp][30]) +"', '"+ str_in(row[temp][21]) +"', '"+ str_in(row[temp][18]) +"', '"+ str_in(cate) +"')"
	db.query(sql)

#  첨부파일
	register_dt = zdate +" "+ ztime

	if row[temp][24]:
		sql = "insert into ASADAL_BOARD_FILE (register_dt, boardName, pkid, filePath, filename) values ('"+str_in(register_dt)+"', '"+ str_in(alias) +"', '"+str_in(row[temp][0])+"', '"+ file_mod(str_in(row[temp][24]))+"', '"+str_in(row[temp][26])+"')"
		db.query(sql)

	if row[temp][25]:
		sql = "insert into ASADAL_BOARD_FILE (register_dt, boardName, pkid, filePath, filename) values ('"+str_in(register_dt)+"', '"+ str_in(alias) +"', '"+str_in(row[temp][0])+"', '"+ file_mod(str_in(row[temp][25]))+"', '"+str_in(row[temp][27])+"')"
		db.query(sql)

# 댓글
sql = "select parent, ismember, name, password, memo, ip, reg_date from " + ztb_memo
db.query(sql)
result = db.store_result()
row = result.fetch_row(0)
if len(row) != 0 :
	for t in range(0, len(row)) :
		zmdate = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(row[t][6])))

		sql = "insert into ASADAL_BOARD_MEMO_"+ alias + " (fk, pw, writer, date, memo, ip) values ('"+ str_in(row[t][0]) +"','"+ str_in(row[t][3]) +"', '"+ str_in(row[t][2]) +"','"+ str_in(zmdate) +"','"+ str_in(row[t][4]) +"','"+ str_in(row[t][5]) +"')"
		db.query(sql)

# 댓글환경설정
sql = "insert into ASADAL_MEMO_CFG (memoName, isMEMO, textColorOfMEMO, borderColorOfMEMO, textFontSizeOfMEMO, textFontFmlOfMEMO, bgColorOfMEMO, isMarkMEMO, writerMEMO, isBadMEMO, memoOrderby, isDateMemo, writerEditMemo, memoAdminEmail, isRecomGraph, graphGood, graphBad) values ('ASADAL_BOARD_MEMO_"+ alias+ "', '0', '#545555', '', '9', 'gulim', '', '0', '1', '0', '0', '1', '1', '', '0', '1', '2')"
db.query(sql)

#알림글
sql = "select name, subject, reg_date, hit, memo, email, ip from " + ztb + " where headnum <= -2000000000 order by headnum DESC, arrangenum ASC"
db.query(sql)
result = db.store_result()
row = result.fetch_row(0)
if len(row) != 0 :
	for t in range(0, len(row)) :
		zpdate = time.strftime("%Y-%m-%d", time.localtime(int(row[t][2])))
		zptime = time.strftime("%H:%M:%S", time.localtime(int(row[t][2])))

		sql = "insert into ASADAL_BOARD_PUB (writer, subject, date, count, contents, email, ip, time, alias) values ('"+ str_in(row[t][0]) +"','"+ str_in(row[t][1]) +"', '"+ str_in(zpdate) +"', '"+ str_in(row[t][3]) +"', '"+ str_in(row[t][4]) +"', '"+ str_in(row[t][5]) +"', '"+ str_in(row[t][6]) +"', '"+ str_in(zptime) +"', '"+ str_in(alias) +"')"
		db.query(sql)


db.close()

"""
	기타
	1 파일
"""
os.system("cp -rf "+ document_root() +"/bbs/data/"+ zalias +"/* "+ document_root() +"/asapro/board/data/")
os.system("chmod 777 "+ document_root() +"/asapro/board/data/*")
print "	<script>alert('제로보드 "+ zalias +"게시판을 아사프로 "+ alias +"게시판으로 옮겼습니다.')</script>"
