#!/usr/bin/python
# -*- coding: cp936 -*-

import os
import sys
import struct
from shutil import *  
from BaseProc import *
import time
import logging
import logger
import dataSerial

logp = logger.FinalLogger.getLogger()

logp.info ('')
logp.info ('')
logp.info ('================================ Begin ================================')

paraLen = len(sys.argv)
if (paraLen != 4):
    logp.debug ('The para must equal to 4')
    logp.debug ('1 : script file (string)')
    logp.debug ('2 : convert data dir (string)')
    logp.debug ('3 : dst file type (int)')
    logp.debug ('4 : max test id(uint)')
    sys.exit(1)

dataSerfiles = sys.argv[1] + "\\dataSerial.txt"
donefiles = sys.argv[1] + "\\Done"

#dataSerfiles文件存在,则删除之
if os.path.exists(dataSerfiles):
    os.remove(dataSerfiles)
    

#Done文件存在,则删除之
if os.path.exists(donefiles):
    os.remove(donefiles)

#创建dataSerial文件,后期会被修改为Done文件
if os.path.exists(dataSerfiles):
    os.remove(dataSerfiles)
#创建
dataSer = dataSerial.DataSerial.getDataSerial(sys.argv[1])

logp.debug(sys.argv[0])
logp.debug(sys.argv[1])
logp.debug(sys.argv[2])
logp.debug(sys.argv[3])

main_py = os.path.dirname(sys.argv[0])
main_py += "\\main.py"


##备份原始的文件夹内容
copytree(sys.argv[1], sys.argv[1]+"_bak_"+time.strftime('%Y%m%d_%H%M%S',time.localtime(time.time())))

curDir = sys.argv[1]

######  除1版本外的其它版本，都为都为ChannelNoMgr.0 以及 ES/0.0  因此转换名字
if os.path.exists(sys.argv[1]+"/flash"):
    for root,dirs,files in os.walk(curDir):
        for eachfiles in files:
            thefile = os.path.join(root,eachfiles)
            if "ChannelNoMgr" in thefile:
                if "ChannelNoMgr.0" not in thefile:
                    os.rename(thefile, thefile+'.0')
            elif (("ES" in thefile) and ("RES" not in thefile)):
                if thefile.endswith(".0"):
                    continue
                else:
                    os.rename(thefile, thefile+'.0')
            else:
                continue

##### 遍历处理所有需要处理的文件，1版本的TestIDMgr不处理，只需要使用
for root,dirs,files in os.walk(curDir):
    for eachfiles in files:
        thefile = os.path.join(root,eachfiles)
        if "TestIDMgr" not in eachfiles and "dataSerial.txt" not in eachfiles and "Done" not in eachfiles:
            logp.debug (thefile)
            cmd = '""%s" "%s" "%s" "%s" "%s""' %(main_py, thefile, sys.argv[2], sys.argv[3], sys.argv[1])
            if (os.system(cmd)):
                logp.debug ("exit with err")
                sys.exit(1)
        else:
            logp.debug("found: " + thefile)

##删除处理的中间文件，因为原始文件有备份，所以可以删除
for root,dirs,files in os.walk(curDir):
    for eachfiles in files:
        thefile = os.path.join(root,eachfiles)
        if ".pre" in eachfiles:
            os.remove(thefile)
        
logp.debug("success!!")
logging.shutdown()
if os.path.exists(dataSerfiles):
    copyfile(dataSerfiles, donefiles)
    if os.path.exists(donefiles):
        fd = open(donefiles, 'w')
        fd.write("success!!!");
        fd.close()
    else:
        logp.error("%s not exist",donefiles)
else:
    logp.error("%s not exist",dataSerfiles)



logp.info ('')
logp.info ('================================ End ================================')
logp.info ('')
logging.shutdown()
sys.exit(0)
