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

import os
import sys
import utils

# 读取 deploy.xml 配置文件定义的 webAppName
webAppName = "${webAppName}"
# TIPS: 执行脚本的路径是在 安装目录 下，对应 deploy.xml 里的 workspace 字段
pkgPath = os.path.join(os.getcwd(), webAppName)
pkg_root = os.getcwd()

def chmodPkg():
    for root,dirs,files in os.walk(pkgPath):
        for file in files:
            if(not file[0] == "."):
                fp = os.path.join(root, file)
                utils.chmod(fp, "755")
        for dir in dirs:
            if(not dir[0] == "."):
                dp = os.path.join(root, dir)
                utils.chmod(dp, "755")

if not os.path.isdir(webAppName):
    sys.stderr.write("错误: 安装检查失败。应用目录 '%s' 不存在。\n" % webAppName)
    sys.exit(1)

if len(os.listdir(webAppName)) == 0:
    sys.stderr.write("错误: 安装检查失败。应用目录 '%s' 存在但为空。\n" % webAppName)
    sys.exit(1)

chmodPkg()

<% if (enableObfuscation && configFileNames && configFileNames.length) { %>
import subprocess
script_dir = os.path.dirname(os.path.abspath(__file__))
confuse_js = os.path.normpath(os.path.join(script_dir, 'js', 'confuse.js'))
confuse_sh = os.path.normpath(os.path.join(script_dir, 'js', 'confuse.sh'))
config_names = [<% configFileNames.forEach(function (cf, i) { %>'<% print(cf) %>'<% if (i < configFileNames.length - 1) { %>, <% } %><% }) %>]

def which(cmd):
    for p in os.environ.get('PATH', '').split(os.pathsep):
        f = os.path.join(p, cmd)
        if os.path.isfile(f) and os.access(f, os.X_OK):
            return f
    return None

for config_name in config_names:
    if which('node'):
        cmd = ['node', confuse_js, webAppName, config_name, pkg_root]
    else:
        cmd = ['bash', confuse_sh, webAppName, config_name, pkg_root]
    ret = subprocess.call(cmd)
    if ret != 0:
        sys.stderr.write("错误: 混淆配置文件失败 (%s.js)。\n" % config_name)
        sys.exit(ret)
<% } %>
