#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from inc import CliTool
import sys, os, datetime, json

app = sys.argv[1]
isIntra = (sys.argv[2] == 'intra')
env = sys.argv[3]
env2 = env
mode = sys.argv[4]
mode2 = mode

isMcPre = (env == 'mc-pre')
module = 'www/' + ((app + '-pre') if isMcPre is True else app)

def verify_app_legal(version_file, pub_app):
    # 检查文件是否存在, 不存在默认允许
    if os.path.exists(version_file) is False:
        return True

    app_mode = None
    with open(version_file, 'r') as file:
        # 解析 JSON 数据
        data = json.load(file)
        # 获取appName的值
        app_mode = data.get('appMode', None)
    
    if app_mode is None:
        return True

    app_name_list = {
        'earth': ['earth'],
        'desktop': ['earth-desktop'],
        'dianjiufang': ['earth-dianjiufang'],
        'easyboss': ['dm-erp'],
        'greatboss': ['greatboss'],
        'dz': ['fetch-bank-v2-dz', 'honor-ksdz-v2', 'honor-xhs-dz', 'honor-xhs-dz-order-v2', 'honor-sphxd-dz'],
        'tbk': ['fetch-bank-v2-tbk', 'honor-xhs-tbk', 'honor-xhs-tbk-order-v2'],
        'ry': ['fetch-bank-v2-ry', 'honor-xhs-ry', ' honor-xhs-ry-order-v2'],
    }
    real_app_mode = next((key for key, value in app_name_list.items() if pub_app in value), None)

    if real_app_mode is None:
        return True
    
    if real_app_mode !=  app_mode:
        print("发布的app {} 和编译生产的appMode {} 不一致, 中断发布".format(pub_app, app_mode))
        return False
    
##joa后台登录的不发atjmax
is_joa_app = app in [
    #'honor-zfb',
    #'jcrm',
    #'honor-zfb-order',
    #'proxy-center',
    #'sms-center',
    #'honor-xhs-order'
]

##腾讯云前后端分离
is_tc_febe_app = app in [
    'greatboss'
] and env in ['real']

##阿里云vpc前端应用
is_ay_febe_app = app in [
    'earth-desktop', 
    'earth-dianjiufang', 
    'earth-chat-analysis', 
    'honor-ksdz-v2', 
    'fetch-bank-v2', 
    'fetch-bank-v2-ms', 
    'fetch-bank-v2-ds', 
    'fetch-bank-v2-dz', 
    'fetch-bank-v2-gold', 
    'fetch-bank-v2-ry', 
    'fetch-bank-v2-tbk', 
    'fetch-bank-v2-ds', 
    'fetch-bank-v2-dmds', 
    'honor-xhs-dz', 
    'honor-xhs-ry', 
    'honor-xhs-tbk',
    'honor-xhs-dz-order-v2',
    'honor-xhs-tbk-order-v2',
    'honor-xhs-ry-order-v2',
    'honor-sphxd-tbk',
    'honor-sphxd-order-dz',
    'honor-sphxd-order-tbk',
    'honor-sphxd-order-ry',
    'honor-ksdz-order-v2',
    'earth-h5-web', 
    'easyboss-h5-web', 
    'honor-ap',
]

is_only_sw_app = app in [
    'help-sass'
]

if app == 'proxy-center' and env == 'pre':
    env = 'pc-pre'

if app in ['xiuxiu-node-api', 'node-video-v2'] and env == 'real':
    env = 'video'

isPcPre = (env == 'pc-pre')
if isPcPre is True:
    module = 'www/' + (app + '-pre')

##兼容joa，预发布和joa是一台机器时候，预发布的程序目录是-pre
if app in [
    'greatboss', 
    'dm-erp', 
    'joy-tbk', 
    'joy-order-tbk',
] and env == 'pre':
    module = 'www/' + (module + '-pre') 

isIntraIp = isIntra
if app in ['dm-erp', 'easyboss-h5']:
    fileName = '/hosts/hosts-easyboss.txt'
    isIntraIp = False
elif app in ['greatboss', 'greatboss-h5']:
    fileName = '/hosts-tc-us-vpc.txt'
    isIntraIp = False
elif app in ['joy-tbk']:
    fileName = '/hosts-honor-jdbk.txt'
elif app in ['joy-order']:
    fileName = '/hosts/hosts-honor-msorder.txt'
elif app in ['gwms']:
    fileName = '/hosts/hosts-wms.txt'
elif app in ['cb-msg-api']:
    fileName = '/hosts/hosts-msg.txt'
elif app in ['forbidden-detect']:
    fileName = '/hosts/hosts-fd.txt'
elif mode == 'web' or is_ay_febe_app is True or is_only_sw_app is True:
    fileName = '/hosts-honor-vpc-sw.txt'
else:
    fileName = '/hosts/hosts-honor-vpc.txt'

filePath = os.path.dirname(sys.argv[0]) + fileName
ipsMap = CliTool.getIpsMap(filePath, isIntraIp, 8873, module)

if app == 'earth' and env == 'real' and mode in ['api', 'real']:
    env += ',erp-real,jst-real'

if app in ['greatboss', 'dm-erp'] and env == 'real':
    env += ',joa-real'

envList = CliTool.getEnvList(env, ipsMap, isIntra)

ips = {}
for env in envList:
    ips = dict(ips, **ipsMap[env])

##sw机器
ips_sw = {}
for key, value in ips.items():
    if '-sw' in key or '-w' in key:
        ips_sw[key] = value

if isIntra is True:
    localPwdFile = '/home/porsche/publish/tjds1.passwd'
else:
    localPwdFile = '/Users/tangjianhui/Documents/publish/tjds1.passwd'

if isIntra is True:
    localSrc = '/alidata/www/' + app + '/'
    if (isMcPre is True) and (app == 'honor'):
        localSrc = '/alidata/www/honor-pre/'
else:
    appLocalSrc = {
        'honor': 'honor.master',
        'earth-chat-analysis': 'earth-chat-mobile-web-analysis.git/dist',
        'easyboss-h5': 'dm-erp-applet.git/build/easyboss-h5',
        'greatboss-h5': 'dm-erp-applet.git/build/greatboss-h5',
    }.get(app, app + '.git')

    localSrc =  CliTool.workspace() + appLocalSrc + '/'

""" version_json = localSrc + 'web/dist/version.json'
if verify_app_legal(version_file=version_json, pub_app=app) is False:
    exit()
 """

##检查pub或者real的时候分支是否是'real', 'master', 'revert'，否则不允许pub
if env in ['pub', 'real'] and mode == 'real' and isIntra is False and app not in [
    'easyboss', 'greatboss', 'dm-erp', 'easyboss-h5', 'greatboss-h5', 'earth-h5-web'
]:
    realLocalSrc = localSrc if os.path.exists(localSrc + ".git") else localSrc + 'api/'
    res = os.popen("cd " + realLocalSrc + " && git branch -a | grep '*' | awk '{print $2}'")
    branch = res.read().strip("\n")

    if any(keyword.lower() in branch.lower() for keyword in ['real', 'master', 'revert']) is False:
        print(("清检查分支: {} 是否为正式发布分支?， 正式发布分支名称需包含 real、master、revert等关键词".format(branch)))
        exit()

exclude_atjmax_exclude = ' --exclude=/api/app/libs/controller/atjmax/* --exclude=/api/app/views/page/atjmax/* '
exclude_atjmax_exclude += ' --exclude=/app/libs/controller/atjmax/* --exclude=/app/views/page/atjmax/* '

#暂时不用排除atjmax
exclude_atjmax_exclude = ''

exclude_ext = ' --exclude=/node_modules/ ' if (isIntra is False and app == 'node-ms-cloud') else ''
exclude_ext += exclude_atjmax_exclude

cmd_tpl = 'rsync -%s --delay-updates {} --stats --port=%s --password-file={} --timeout=120 {} {} {} www@%s::%s/'

def build_exclude_ext(mode):
    if mode == 'api':
        return ' --include=/api/ --exclude=/web/* ' + exclude_atjmax_exclude
    
    if mode == 'web':
        return ' --exclude=/api/* --include=/web/dist/ --include=/web/distv1/ '

    if mode == 'joa':
        return ' --include=/api/ --exclude=/web/* '
    
    return ''

def pubish_sw(code_type, mode_type):
    if code_type == 'api':
        return 
    
    if not ips_sw:
        print("sw 机器为空")
        exit()
        
    exclude_ext_web =  build_exclude_ext('web')
    Ct = CliTool()

    cmd_tpl_web_no_del =  cmd_tpl.format('', localPwdFile,  CliTool.excludeFile(), exclude_ext_web, localSrc)
    print("\n\n正在发布[SW]机器 and no --del ...")
    Ct.publish(ips_sw, mode_type, cmd_tpl_web_no_del)
    
    if code_type == 'web':
        cmd_tpl_web =  cmd_tpl.format('--del', localPwdFile,  CliTool.excludeFile(), exclude_ext_web, localSrc)
        print("\n\n正在发布[SW]机器")
        Ct.publish(ips_sw, mode_type, cmd_tpl_web)

if mode in ['api', 'web']:
    exclude_ext += build_exclude_ext(mode)
    mode = sys.argv[5]
    

##joa机器发布
if is_joa_app and 'joa-real' in ipsMap:
    joa_ips = ipsMap['joa-real']
    joa_ext = build_exclude_ext('joa')
    real_mode = sys.argv[5] if mode2 in ['web', 'api'] else mode2
    cmdTpl = cmd_tpl.format('--del', localPwdFile,  CliTool.excludeFile(), joa_ext, localSrc)
    Ct = CliTool()
    print("正在发布joa机器 ...")
    Ct.publish(joa_ips , real_mode, cmdTpl)

##real或者api发布
if not ips:
    print("机器为空")
    exit()

if is_tc_febe_app or is_ay_febe_app:
    pubish_sw(mode2, mode)
    ##前端仅发布web机器
    if mode2 == 'web':
        exit()

##其他正常发布
cmd_tpl_all = cmd_tpl.format('--del', localPwdFile,  CliTool.excludeFile(), exclude_ext, localSrc)
Ct = CliTool()
syntax_check = False if isIntra is True else True
Ct.publish(ips, mode, cmd_tpl_all, php_syntax_check = syntax_check)