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

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

APP_HELP_WEB = 'help-web'
APP_EARTH_CMS_ADMIN = 'earth-blog-admin-ssr'
APP_EARTH_CMS = 'earth-blog-ssr'

target_app_dir = {
    APP_HELP_WEB: 'help-sass-ssr'
}.get(app, app)

module = 'www/' + target_app_dir

fileName =  '/conf/hosts/hosts-ay-node-ssr.txt'
filePath = os.path.dirname(sys.argv[0]) + fileName

ipsMap = CliTool.getIpsMap(filePath, isIntra, 8873, module)

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

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

def checkDistPath(distPath):
    ##check dist is empty
    print(os.path.exists(distPath))
    if os.path.exists(distPath) is False:
        print("{} does not exist".format(distPath))
        return False

    if len(os.listdir(distPath)) == 0:
        print("Folder {} is empty".format(distPath))
        return False
    
    return True 

def execCommand(cmd, outputResp = False):
    outputStr = ''
    nvm_dir = os.environ.get('NVM_DIR')
    command = "source {}/nvm.sh && {}".format(nvm_dir, cmd)
    #command = "source ~/.nvm/nvm.sh && {}".format(cmd)
    process = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while process.poll() is None:
        line = process.stdout.readline()
        line = line.strip()
        if line:
            respStr = line.decode('utf8', 'ignore')
            if outputResp is True:
                print(respStr)
            else:
                outputStr += respStr

    return outputStr

nvm_dir = os.environ.get('NVM_DIR')

## check nvm version
nvmVersion = execCommand('nvm -v')
if '0.3' not in nvmVersion:
    print("NVM 未安装，请先安装nvm")
    exit()

## check node -version
nodeVersion = 'v20'
checkResp = execCommand("nvm ls {}".format(nodeVersion))
if 'N/A' in checkResp:
    print("Node.js {} is not installed. Please install it using NVM and try again.".format(nodeVersion))
    exit()

exclude_ext = '--include=/dist/ --exclude=/*'
localPwdFile = '/Users/tangjianhui/Documents/publish/tjds1.passwd'

##node api path
localSrc =  CliTool.workspace()  + app + '.git/'
yarnBuildCmd  = {
    APP_HELP_WEB: 'build:help',
    APP_EARTH_CMS_ADMIN: 'build:earth-blog-admin',
    APP_EARTH_CMS: 'build:earth-blog-website',
}.get(app, False)

if yarnBuildCmd is False:
    print('{} app bian 编译命令未找到'.format(app))
##apicmd
ssrCmd = "export PUPPETEER_SKIP_DOWNLOAD=true; cd {} && nvm use {} && yarn && yarn {}".format(localSrc, nodeVersion, yarnBuildCmd)

execCommand(ssrCmd, True)

#check dist is empty
distFsDir  = {
    APP_EARTH_CMS_ADMIN: 'packages/admin/dist/',
    APP_EARTH_CMS: 'packages/website/dist/',
}.get(app, 'dist/')

distPath = localSrc + distFsDir
if checkDistPath(distPath) is False:
    print("编译目录dist 不存在请检查")
    exit()


cmdTpl = 'rsync -%s --delay-updates --del --stats --port=%s --password-file={} --timeout=120 {} {} {}  www@%s::%s/'.format(localPwdFile, CliTool.excludeFile(), exclude_ext, localSrc)

Ct = CliTool()
Ct.publish(ips, mode, cmdTpl)
