#!/usr/bin/env groovy

def projectProperties = [
        [$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '5']],
        parameters([
                string(name: 'REGISTRY_URL', defaultValue: 'harbor.sino-assist.com', description: 'docker harbor register url'),
                string(name: 'NAMESPACE', defaultValue: 'crm1', description: 'NAMESPACE'),
                string(name: 'deploy_server', description: '机器ip'),
                string(name: 'profile', defaultValue: 'dev', description: 'profile'),
                booleanParam(name: 'yarnInstall', description: '是否更新node_modules'),
                string(name: 'backUrl', defaultValue: 'https://api1.sino-assist.com', description: 'backend server url')
        ])
]

node {
    def workspace = pwd()
    def DOCKER_CREDENTIAL_ID = 'harbor'

    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('docker-login') {
       withCredentials([usernamePassword(passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME', credentialsId: "${DOCKER_CREDENTIAL_ID}",)]) {
            sh "echo '$DOCKER_PASSWORD' | docker login ${params.REGISTRY_URL} -u '$DOCKER_USERNAME' --password-stdin"
       }
    }

    stage('docker-build') {
        sh " docker build -f jenkins/swarm/Dockerfile -t ${params.REGISTRY_URL}/new-sino/supplier-dispatch-h5:${params.NAMESPACE} ."
    }

    stage('docker-push') {
        sh "docker push ${params.REGISTRY_URL}/new-sino/supplier-dispatch-h5:${params.NAMESPACE}"
    }

    stage('deploy') {
        String yml = docker_service_param(params)
        String serverName = "${params.NAMESPACE}_ns_supplier-dispatch-h5"
        String ymlFile = "/data/swarm/${serverName}.yml"
        String deploy = "ssh root@${params.deploy_server} \"touch ${ymlFile} && echo '''${yml}''' > ${ymlFile} && docker stack  deploy -c ${ymlFile}  ${serverName} --with-registry-auth\""
        echo deploy
        sh deploy
    }
}


def makeYML(params){
    def ymlTemp = '''
version: \\"3.8\\"
services:
    svc:
        image: ${IMAGE}
        environment:
            - TZ=Asia/Shanghai
        ports:
            - '8031:8080'
        deploy:
            mode: replicated
            replicas: ${replicas}
            restart_policy:
                condition: on-failure
                delay: 5s
                max_attempts: 3
            update_config:
                order: start-first

            resources:
                limits:
                    cpus: \\"${limitCpu}\\"
                    memory: ${limitMemory}
                reservations:
                    cpus: \\"${reservationsCpu}\\"
                    memory: ${reservationsMemory}
            placement:
                constraints:
                  - "node.labels.${namespace}_${projectName}==1"
networks:
    default:
        name: ${namespace}
        external: true
'''
    def dockerComposeTemplate = new groovy.text.SimpleTemplateEngine().createTemplate(ymlTemp)
    return dockerComposeTemplate.make(params)
}


def docker_service_param(_params){
    def params = [
            namespace: _params.NAMESPACE,
            projectName: "supplier-dispatch-h5",
            IMAGE: "${_params.REGISTRY_URL}/new-sino/supplier-dispatch-h5:${_params.NAMESPACE}",
            profile: _params.profile,
            replicas: 1,             // 副本数量
            reservationsCpu: 0.1,        // 保留cpu
            limitCpu: 1,               // 最大cpu
            reservationsMemory: "300M",  // 保留内存
            limitMemory: "500M"          // 最大内存
    ]
    echo "params ${params}"

    return makeYML(params)
}
