#!/usr/bin/env groovy

def projectProperties = [
        [$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '5']],
        parameters([
                string(name: 'targetIps', description: '机器ip'),
                string(name: 'backUrl', description: '后台地址'),
                choice(
                        name: 'activeProfile',
                        description: '部署环境',
                        choices: ['dev', 'prod']
                ),
                booleanParam(name: 'yarnInstall', description: '是否更新node_modules'),
        ])
]

node {
    def workspace = pwd()

    stage('Initialize') {
        echo 'Initializing...'
        def node = tool name: 'nodejs-v12', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation'
        env.PATH = "${node}/bin:${env.PATH}"
    }

    stage('checkout') {
        checkout scm
    }

    stage('build') {
            if(params.yarnInstall == true){
                sh "yarn config set registry https://mirrors.huaweicloud.com/repository/npm/"
                sh "yarn config set disturl https://mirrors.huaweicloud.com/nodejs/"
                sh "yarn config set electron_mirror https://mirrors.huaweicloud.com/electron/"
                sh "yarn config set registry https://registry.npm.taobao.org"
                sh "yarn config set disturl https://npm.taobao.org/dist"
                sh "yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/"
                sh "yarn"
            }
            String backUrl = params.backUrl
            if(params.activeProfile == 'prod'){
                sh "sed -i 's|VUE_APP_BACK_REST_URL_PLACE_HOLDER|${backUrl}|' ${workspace}/.env.prod"
                sh "yarn build-prod"
            }else{
                sh "sed -i 's|VUE_APP_BACK_REST_URL_PLACE_HOLDER|${backUrl}|' ${workspace}/.env.alpha"
                sh "yarn build"
            }
    }

    stage('scp') {
         sh 'tar zcvf supplier-dispatch-h5.zip ./dist/'

          for (String ip : "${params.targetIps}".split(",")) {
                 echo "ssh deploy ${ip}"
                 sh "ssh root@${ip} 'bash -s' < '${workspace}/jenkins/file_exist.sh' supplier-dispatch-h5"

                 sh "scp supplier-dispatch-h5.zip root@${ip}:/zd/supplier-dispatch-h5/"
                 sh "ssh root@${ip} 'sudo rm -rf /zd/supplier-dispatch-h5/dist && sudo tar -zxvf /zd/supplier-dispatch-h5/supplier-dispatch-h5.zip  -C  /zd/supplier-dispatch-h5/ '"
                 sh "ssh root@${ip} 'sudo bash -s' < '${workspace}/jenkins/docker-compose-restart.sh'"
          }
    }
}
