#!/usr/bin/env groovy
pipeline {
  agent any

  environment {
    GIT_REPO_URL = 'https://code-c.cmft.com/CMEW-GISOpManagement/manager-web-crcc.git'
    GIT_CRED_ID = 'd336cb92-b512-43ec-a135-253679621736'
  }
  parameters {
    gitParameter branchFilter: 'origin/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH_TAG'
  }

  options {
    // 表示保留10次构建历史
    buildDiscarder(logRotator(numToKeepStr: '10'))
    // 不允许同时执行流水线，被用来防止同时访问共享资源等
    disableConcurrentBuilds()
    // 设置流水线运行的超时时间, 在此之后，Jenkins将中止流水线
    timeout(time: 30, unit: 'MINUTES')
    // 输出构建的时间信息
    timestamps()
  }

  stages {
    stage('Checkout') {
      steps {
        echo '****************************** 获取代码 ******************************'
        git credentialsId: GIT_CRED_ID, url: GIT_REPO_URL, branch: "${params.BRANCH}"
      }
    }
    stage('Build') {
      steps {
        echo '****************************** 打包 ******************************'
        nodejs('nodejs16') {
          sh '''
            ls
            yarn install
            yarn build:prod
          '''
        }
      }
    }
    stage('Deploy') {
      parallel {
        stage('部署') {
          steps {
            echo '****************************** 部署 ******************************'
            script {
              def username = 'root'
              def remoteHost = '172.16.200.83'
              def remoteDir = '/home/ztj/cockpitv/'
              sh """
                scp -r -o StrictHostKeyChecking=no dist/* ${username}@${remoteHost}:${remoteDir}
                ssh -o StrictHostKeyChecking=no ${username}@${remoteHost} "cd ${remoteDir}; pwd; ls -l"
              """
            }
          }
        }
      }
    }
  }

  post {
    success {
      echo '****************************** 发布成功 ******************************'
    }
    failure {
      echo '****************************** 发布失败 ******************************'
    }
    unstable {
      echo '****************************** 发布失败 ******************************'
    }
  }
}
