#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 主系统安装时 install 的执行目录应该到 /html
# 子系统安装时 install 的执行目录应该到 /html/主系统目录名

# 发布物中的源码部分应该统一放到 source 目录下

import json
import os
import re
import sys
import utils

try:
    reload(sys)
    sys.setdefaultencoding("utf8")
except:
    print("Failed to perform module reload, continue installation")


name = "{{name}}"
type = "{{type}}"
# 读取 deploy.xml 配置文件定义的 webAppName
webAppName = "${webAppName}"

def install(name, type):
    conf = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), "conf")

    manifest = ""

    for file in os.listdir(conf):
        if(re.match(r'manifest\.[0-9]+\.json', file)):
            manifest = file

    if(manifest == ""):
        if(type == "bizframe"):
            os.popen("cp -rf ./tmp/source ./" + name)
        elif(type == "subsystem"):
            os.popen("cp -rf ./tmp/source ./")
    else:
        file = open(os.path.join(conf, manifest), "rb")
        fileJson = json.load(file)

        for x in fileJson:
            destinationdir = ""
            source = ""

            if(type == "bizframe"):
                destinationdir = "./" + webAppName + "/" + fileJson[x]["dir"]
                source = "./tmp/source/" + fileJson[x]["path"]
            elif(type == "subsystem"):
                destinationdir = "./" + fileJson[x]["dir"]
                source = "./tmp/source/" + fileJson[x]["path"]

            if not (os.path.exists(destinationdir)):
                os.makedirs(destinationdir)

            if(os.path.exists(source)):
                os.popen("cp -rf " + source + ' ' + destinationdir)

    os.popen("rm -rf tmp")


utils.clear(webAppName, type)

# SEE 在脚本下发的时候会保留 scripts 目录下的内容，造成 conf 中存在多份 manifest
os.popen("rm -rf ./scripts/" + name)
os.popen("cp -rf ./tmp/scripts/" + name + " ./scripts/" + name)

install(name, type)
