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

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

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

import json
import os
import re
import sys
import utils

# 在 Python 2 中导入额外模块
if sys.version_info[0] == 2:
    try:
        from io import open
    except ImportError:
        pass
# 仅在Python 2中设置默认编码
if sys.version_info[0] == 2:
    try:
        reload(sys)
        sys.setdefaultencoding("utf8")
    except Exception as e:
        print("执行模块重载失败，原因：", e)
        print("继续安装...")

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

def copy_source(deploy_type, name):
    if deploy_type == "bizframe":
        os.system("cp -rf ./tmp/source ./" + name)
    elif deploy_type == "subsystem":
        os.system("cp -rf ./tmp/source ./")

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

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

    if not manifest:
        copy_source(deploy_type, name)
    else:
        with open(os.path.join(conf, manifest), "rb") as f:
            fileJson = json.load(f)

        for x in fileJson:
            if deploy_type == "bizframe":
                destinationdir = "./" + webAppName + "/" + fileJson[x]["dir"]
                source = "./tmp/source/" + fileJson[x]["path"]
            elif deploy_type == "subsystem":
                destinationdir = "./" + fileJson[x]["dir"]
                source = "./tmp/source/" + fileJson[x]["path"]
            else:
                continue

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

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

    os.system("rm -rf tmp")

utils.clear(webAppName, deploy_type)

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

install(name, deploy_type)
