from __future__ import print_function
import os
import sys
import subprocess
import datetime
import pickle
ROUTE_GIT = 'https://hitorigochi:h1kar1t0kage@github.com/mlfcomp/'

GIT_TMP_PATH = 'git'

DIC_PATH = './.DIC_MAKEPACKAGE'
#INSTALL_SCRIPT = "Install_4_0_py3.py"
INSTALL_SCRIPT = "Install_4_0_py3_2004.py"
UTSUSEMI_RELEASE = "4.0"
#DISTVER = "Ubuntu_1604_1804LTS_PY3"
DISTVER = "Ubuntu_1604_2004LTS_PY3"

PACK_LIST = { 'manyo-core':("manyo","master"),
              'manyo-core-034':("manyo","0.3.4"),
              'utsusemi-core-037':("Utsusemi","0.3.7"),
              'utsusemi-core-40':("Utsusemi","4.0"),
              'ugao-master':("uGao","master"),
              'emaki-master':("emaki","master"),
              'utsusemi-ENG-master':("Utsusemi-ENG","master"),
              'utsusemi-ENG-40':("Utsusemi-ENG","4.0"),
              'utsusemi-TKtools-master':("Utsusemi-TKtools","master"),
              'utsusemi-SAS-master':("Utsusemi-SAS","master"),
              'utsusemi-SAS-40':("Utsusemi-SAS","4.0"),
              'utsusemi-DNA-master':("Utsusemi-DNA","master"),
              }

"""
RELEASE_LIST = {'4.0':['manyo-core','utsusemi-core-40','ugao-master','emaki-master','utsusemi-ENG-master','utsusemi-TKtools-master','utsusemi-SAS-master','utsusemi-DNA-master'],
                '0.3.7':['manyo-core','utsusemi-core-037','ugao-master','emaki-master','utsusemi-ENG-master','utsusemi-TKtools-master','utsusemi-SAS-master','utsusemi-DNA-master']
}n
"""
RELEASE_LIST = {'4.0':['manyo-core-034','utsusemi-core-40','ugao-master','emaki-master','utsusemi-ENG-40','utsusemi-TKtools-master','utsusemi-SAS-40','utsusemi-DNA-master'],
                '0.3.7':['manyo-core-034','utsusemi-core-037','ugao-master','emaki-master','utsusemi-ENG-master','utsusemi-TKtools-master','utsusemi-SAS-master']
}
def updateGitRepo( repo_name, branch ):
    print("--- updateGitRepo")
    com = "cd %s;git fetch %s"%(os.path.join(GIT_TMP_PATH,repo_name), os.path.join( ROUTE_GIT, repo_name ))
    os.system( com )
    com = "cd %s;git pull %s %s"%(os.path.join(GIT_TMP_PATH,repo_name), os.path.join( ROUTE_GIT, repo_name ), branch )
    os.system( com )

def getGitLastUpdate( repo_name, branch ):
    print("--- getGitLastUpdate")
    current_path = os.getcwd()
    os.chdir(os.path.join(GIT_TMP_PATH,repo_name))
    #v=str( subprocess.check_output("git log -b %s -n 1"%(branch), universal_newlines=True ) )
    #v=str( subprocess.check_output(["git","log","-b",branch,"-n""1"], universal_newlines=True ) )
    os.system( "git checkout %s"%(branch) )
    v=str( subprocess.check_output(["git","log","-n""1"], universal_newlines=True ) )
    #print( "v="+v )
    os.chdir(current_path)
    mon_dic = {"Jan":1,"Feb":2,"Mar":3,"Apr":4,"May":5,"Jun":6,"Jul":7,"Aug":8,"Sep":9,"Oct":10,"Nov":11,"Dec":12}
    s=v.split("\n")
    #print( "s=",s )

    date_info = ""
    for a_s in s:
        if a_s.find("Date:")==0:
            date_info = a_s
    if date_info=="":
        raise UserWarning(" Git version info is invalid." )

    ll=[]
    for k in date_info.split(" "):
        if k!="" and k!="Date:":
            if k in mon_dic.keys():
                ll.append( mon_dic[k] )
            else:
                ll.append( k )
                
    t=ll[3].split(':')
    #print( "ll=",ll )
    #print( "t=",t )
    p=datetime.datetime(int(ll[4]),int(ll[1]),int(ll[2]),int(t[0]),int(t[1]),int(t[2]))
    return p


def addDict( filepath, title, repo_name, branch ):
    print("--- addDict")
    rev_dic = getDict( filepath )
    #print("rev_dic after getDict=",rev_dic)
    add_dic = None
    p=getGitLastUpdate( repo_name, branch )
    add_dic=( repo_name, branch, p )
    rev_dic[title] = add_dic

    fo = open(filepath,"wb")
    pickle.dump( rev_dic,fo)
    fo.close()
        
            
def getDict( filepath ):
    print("--- getDict")
    rev_dic = {}
    if os.path.exists( filepath ):
        try:
            fo = open(filepath,"rb")
            rev_dic = pickle.load(fo)
            fo.close()
        except:
            print("False to read %s"%filepath)
    return rev_dic


def checkUpdate(filepath, title, repo_name, branch):
    print("--- checkUpdate")
    rev_dic = getDict( filepath )
    if (rev_dic==None):
        return (False,False)

    if title in rev_dic:
        info = rev_dic[title]
        if info[0]!=repo_name or info[1]!=branch:
            addDict( filepath, title, repo_name, branch )
            return (True,True)
        
        p_dic = info[2]
        p_git = getGitLastUpdate( repo_name, branch )
        if p_dic<p_git:
            return (True,True)
        else:
            return (True,False)
    else:
        return (False,False)


def makePackage(filepath,key_release):
    print("-- Make Package --")
    rev_dic = getDict(filepath)
    rq_pack_list = RELEASE_LIST[key_release]
    os.system( "mkdir -p tmp" )
    
    dt = datetime.datetime.now()
    date_s = "%04d%02d%02d"%(dt.year,dt.month,dt.day)
    date_s = date_s[2:]
    dir_name = "Utsusemi_%s_%s_%s"%(UTSUSEMI_RELEASE,date_s,DISTVER)
    dir_src = os.path.join( dir_name,"src" )
    os.system( "mkdir -p %s"%dir_src )
    
    manyo_core_rev = 0
    utsusemi_ver = ""
    sas_ver = ""
    dna_ver = ""
    
    coms = []
    for rq_pack in rq_pack_list:
        repo_name,branch=PACK_LIST[rq_pack]
        info = rev_dic[rq_pack]

        #coms.append( "cd tmp;git clone -b %s --depth 1 %s%s.git "%(branch,ROUTE_GIT,route) )
        
        if rq_pack.find("manyo-core")==0:
            coms.append( "cp -r %s/manyo %s/manyo-core"%(GIT_TMP_PATH,dir_src) )
            coms.append( "rm -rf %s/manyo-core/.git"%(dir_src) )
            manyo_core_rev = info[2].strftime('%Y%m%d')
        elif rq_pack.find("utsusemi-core")==0:
            coms.append( "cp -r %s/Utsusemi/manyo %s/manyo-utsusemi"%(GIT_TMP_PATH,dir_src) )
            coms.append( "rm -rf %s/manyo-utsusemi/.git"%(dir_src) )
            utsusemi_ver = info[2].strftime('%Y%m%d')
            #coms.append( 'cd %s/manyo-utsusemi;python ../../../script/insertRevNo.py "manyo" "r%s"'%(dir_src,utsusemi_ver) )
            coms.append( "mkdir -p %s/python-utsusemi"%(dir_src) )
            coms.append( "cp -r %s/Utsusemi/python-utsusemi %s/python-utsusemi/utsusemi"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi/python-utsusemi-SIK %s/python-utsusemi/utsusemi/SIK"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi/python-utsusemi-AMR %s/python-utsusemi/utsusemi/AMR"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi/python-utsusemi-HPN %s/python-utsusemi/utsusemi/HPN"%(GIT_TMP_PATH,dir_src) )
        elif rq_pack.find('ugao')==0:
            ugao_branch = info[1]
            ugao_ver = info[2].strftime('%Y%m%d')
            coms.append( "mkdir -p %s/python-ugao"%(dir_src) )
            coms.append( "cp -r %s/uGao %s/python-ugao/"%(GIT_TMP_PATH,dir_src) )
            coms.append( "rm -rf %s/python-ugao/uGao/.git"%(dir_src) )
        elif rq_pack.find('emaki')==0:
            coms.append( "cp -r %s/emaki %s/python-emaki"%(GIT_TMP_PATH,dir_src) )
            coms.append( "rm -rf %s/python-emaki/.git"%(dir_src) )
        elif rq_pack.find('utsusemi-ENG')==0:
            coms.append( "cp -r %s/Utsusemi-ENG/manyo %s/manyo-emaki"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-ENG/python-utsusemi-ENG %s/python-utsusemi/utsusemi/ENG"%(GIT_TMP_PATH,dir_src) )
        elif rq_pack.find('utsusemi-TKtools')==0:
            coms.append( "cp -r %s/Utsusemi-TKtools/manyo %s/manyo-TKtools"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-TKtools/python-utsusemi-TKtools %s/python-utsusemi/utsusemi/TKtools"%(GIT_TMP_PATH,dir_src) )
        elif rq_pack.find('utsusemi-SAS')==0:
            sas_branch = info[1]
            sas_ver = info[2].strftime('%Y%m%d')
            coms.append( "cp -r %s/Utsusemi-SAS/manyo %s/manyo-SAS"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-SAS/python-utsusemi-SAS %s/python-utsusemi/utsusemi/SAS"%(GIT_TMP_PATH,dir_src) )
        elif rq_pack.find('utsusemi-DNA')==0:
            dna_branch = info[1]
            dna_ver = info[2].strftime('%Y%m%d')
            coms.append( "cp -r %s/Utsusemi-DNA/manyo %s/manyo-DNA"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-DNA/lib-levmar %s/lib-levmar"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-DNA/manyo-LevmarTools %s/manyo-LevmarTools"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-DNA/python-utsusemi-DNA %s/python-utsusemi/utsusemi/DNA"%(GIT_TMP_PATH,dir_src) )
            coms.append( "cp -r %s/Utsusemi-DNA/environ-home %s/environ-DNA"%(GIT_TMP_PATH,dir_src) )
        else:
            pass

    coms.append( "cd %s;echo %s > version.txt"%( dir_src,("date:"+date_s) ) )
    coms.append( 'cd %s;echo "Manyo-lib rev=%s" >> version.txt' %( dir_src,manyo_core_rev ) )
    coms.append( 'cd %s;echo "uGao %s(%s)" >> version.txt' %( dir_src,ugao_branch,ugao_ver ) )
    coms.append( 'cd %s;echo "Utsusemi %s(%s)" >> version.txt' %( dir_src,UTSUSEMI_RELEASE,utsusemi_ver ) )
    if sas_ver!="":
        coms.append( 'cd %s;echo "SAS %s(%s)" >> version.txt' %( dir_src,sas_branch,sas_ver ) )
    if dna_ver!="":
        coms.append( 'cd %s;echo "DNA %s(%s)" >> version.txt' %( dir_src,dna_branch,dna_ver ) )
    coms.append( "cp script/%s %s/Install.py"%(INSTALL_SCRIPT,dir_name) )
    coms.append( "tar czvf %s.tar.gz %s"%(dir_name,dir_name) )
    #coms.append( "zip %s.zip -r %s"%(dir_name,dir_name) )
    coms.append( "rm -rf %s"%(dir_name) )
    coms.append( "rm -rf tmp/*" )
    
    for com in coms:
        print(com)
        if os.system(com)!=0:
            print( "!!! ERROR !!!" )
            print( "command = %s"%com )
            isGoodEnd = False
            break
        else:
            isGoodEnd = True
    
    return (isGoodEnd,dir_name)

def makePage(fname):
    print("-- Make Page --")
    
def showUsage():
    print( "Usage : python3 %s <release tag> [<options>]"%(sys.argv[0]) )
    print( "   " )
    print( "      <release tag> : 4.0/0.3.7 " )
    print( "      <options>" )
    print( "            --force : make package by force" )
    print( "                      If not, make pakage when any updated source codes" )
    print( "            --new   : not update but make new from source" )

if __name__ == '__main__':
    if sys.version.split(" ")[0]<"3.0.0":
        print( "ERROR : This script requires Python 3.x")
        print( "        Your python version is %s"%(sys.version.split(" ")[0]))
        sys.exit(-1)

    if len(sys.argv)==1:
        showUsage()
        sys.exit(1)
    
    isRequiredUpdate=False
    isNew = False
    key_release = ""
    print( sys.argv )
    for an_arg in sys.argv:
        if an_arg.find("--")==0:
            if an_arg=="--force":
                isRequiredUpdate=True
            if an_arg=="--new":
                isNew = True
        elif an_arg in RELEASE_LIST.keys():
            key_release = an_arg

    flag=False
    if key_release=="":
        showUsage()
        sys.exit(1)
    else:
        print( "key_release="+key_release )
        if isNew:
            print("--new")
            for title in RELEASE_LIST[key_release]:
                if title in PACK_LIST.keys():
                    repo_name,branch = PACK_LIST[title]
                    print( "repo_name,branch = %s, %s"%(repo_name,branch))
                    addDict( DIC_PATH, title, repo_name, branch )
        
        elif isRequiredUpdate:
            for title in RELEASE_LIST[key_release]:
                if title in PACK_LIST.keys():
                    repo_name,branch = PACK_LIST[title]
                    print( "repo_name="+repo_name+","+branch)
                    updateGitRepo( repo_name, branch )
                    addDict( DIC_PATH, title, repo_name, branch )
            flag,fname=makePackage(DIC_PATH,key_release)

        else:            
            for title in RELEASE_LIST[key_release]:
                if title in PACK_LIST.keys():
                    repo_name,branch = PACK_LIST[title]
                    updateGitRepo( repo_name, branch )
                    status, isUpdate = checkUpdate(DIC_PATH, title, repo_name, branch)
                    if status and isUpdate:
                        addDict( DIC_PATH, title, repo_name, branch )
                        isRequiredUpdate = True
                else:
                    print("title(%s) is invalid."%(title))
                    sys.exit(1)
                
                #if isRequiredUpdate:
                #    break

            if isRequiredUpdate:
                flag,fname=makePackage(DIC_PATH,key_release)

    if flag:
        makePage(fname)

