pipeline {
  agent any
  options {
    skipDefaultCheckout true
  }
  stages {
    stage('checkout') {
      steps {
        checkout scm
      }
    }
    stage('npm install') {
      steps {
        script {
          sh "docker run -i --rm -v ${env.WORKSPACE}:/usr/src/workspace -w /usr/src/workspace mayan31370/docker-image-nodejs:14 cnpm install"
        }
      }
    }
    stage('npm build') {
      steps {
        script {
          sh "docker run -i --rm -v ${env.WORKSPACE}:/usr/src/workspace -w /usr/src/workspace mayan31370/docker-image-nodejs:14 cnpm run build:h5"
        }
      }
    }
    stage('build docker image') {
      steps {
        script {
          sh "aws ecr get-login-password --region cn-north-1 | docker login --username AWS --password-stdin 226381024927.dkr.ecr.cn-north-1.amazonaws.com.cn"
          sh "docker build -t aibaidu/arrive-h5 ."
        }
      }
    }
    stage('push docker image') {
      steps {
        script {
          sh "docker tag aibaidu/h5:latest 226381024927.dkr.ecr.cn-north-1.amazonaws.com.cn/aibaidu/arrive-h5:latest"
          sh "docker push 226381024927.dkr.ecr.cn-north-1.amazonaws.com.cn/aibaidu/arrive-h5:latest"
        }
      }
    }
    // stage('deploy') {
    //   steps {
    //     script {
    //       sh "ssh -o StrictHostKeyChecking=no aibaidu-admin './deploy-h5.sh'"
    //     }
    //   }
    // }
    
        stage('Send notify'){
            steps{
                script{
                    def content = "### 公众号H5\n<font color='info'>部署完成</font>" + getChangeString()
                    sh "curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=743fe5f4-d4cf-4906-8aa5-93353a4287da' -H 'Content-Type: application/json' -d '{\"msgtype\": \"markdown\",\"markdown\": {\"content\": \"${content}\",\"mentioned_list\":[\"@all\"]}}'"
                }
            }
        }
    }
}
@NonCPS
def getChangeString() {
    MAX_MSG_LEN = 100
    def changeString = ""
    echo "Gathering SCM changes"
    def changeLogSets = currentBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            truncated_msg = entry.msg.take(MAX_MSG_LEN)
            changeString += " - ${truncated_msg} [${entry.author}]\n"
        }
    }
    if (!changeString) {
        changeString = " - No new changes"
    }
    return changeString
}
