pipeline {
  agent any
  stages {
    stage('检出') {
      steps {
        checkout([$class: 'GitSCM',
        branches: [[name: GIT_BUILD_REF]],
        userRemoteConfigs: [[
          url: GIT_REPO_URL,
          credentialsId: CREDENTIALS_ID
        ]]])
      }
    }
    stage('安装依赖') {
      steps {
        sh 'cd ./packages/utils && pnpm install'
        sh 'cd ./packages/design && pnpm install'
      }
    }
    stage('编译') {
      steps {
        sh 'cd ./packages/utils && pnpm build'
        sh 'cd ./packages/design && pnpm build'
        sh 'cd ./packages/design && tar -zcf ./dist.tar.gz ./dist'
      }
    }
    stage('上传到服务器目录') {
      steps {
        echo '部署中...'
        script {
          def remote = [:]
          remote.name = 'ourschool'
          remote.allowAnyHosts = true
          remote.port = 22

          // 把「CODING 凭据管理」中的「凭据 ID」填入 credentialsId，而 id_rsa 无需修改
          withCredentials([usernamePassword(credentialsId: "165db332-d998-46b9-88b5-86d429689c2d", "passwordVariable": "password", "usernameVariable": "userName")]) {
            remote.user = userName
            remote.password = password

            if (env.BRANCH_NAME == 'test') {
              remote.host = 'testing-srv-01.ourschool.cc'
              echo '部署到测试环境'

              sshPut remote: remote, from: './packages/design/dist.tar.gz', into: '/home/www-data/public_html/test-app.ourschool.cc/'

              sshCommand remote: remote, command: "tar -zxf /home/www-data/public_html/test-app.ourschool.cc/dist.tar.gz -C /home/www-data/public_html/test-app.ourschool.cc/"
              sshCommand remote: remote, command: "rm -f /home/www-data/public_html/test-app.ourschool.cc/dist.tar.gz"
              sshCommand remote: remote, command: "rm -rf /home/www-data/public_html/test-app.ourschool.cc/design/ && mv /home/www-data/public_html/test-app.ourschool.cc/dist/ /home/www-data/public_html/test-app.ourschool.cc/design/"
            } else {
              remote.host = 'prd-srv-01.ourschool.cc'
              echo '部署到正式环境'

              sshPut remote: remote, from: './packages/design/dist.tar.gz', into: '/home/www-data/public_html/app.ourschool.cc/'

              sshCommand remote: remote, command: "tar -zxf /home/www-data/public_html/app.ourschool.cc/dist.tar.gz -C /home/www-data/public_html/app.ourschool.cc/"
              sshCommand remote: remote, command: "rm -f /home/www-data/public_html/app.ourschool.cc/dist.tar.gz"
              sshCommand remote: remote, command: "rm -rf /home/www-data/public_html/app.ourschool.cc/design/ && mv /home/www-data/public_html/app.ourschool.cc/dist/ /home/www-data/public_html/app.ourschool.cc/design/"
            }

          }
        }

        echo '部署完成'
      }
    }
  }
}
