pipeline {
    agent any
    
    stages {
        stage('checkout') {
            steps {
                dir("${env.WORKSPACE}/code"){
                    git branch: branch,credentialsId: 'cd13504d-d7eb-433f-be4b-4cbeedf0372d', url: 'http://47.92.161.104:10080/shuzhan/jp-employment-portal.git'
                }
            }
        }
        
        stage('package') {
            steps {
                nodejs('nodejs12') {
                    //sh 'npm install cnpm -g --registry=https://registry.npm.taobao.org'
                    //sh 'cnpm -v'

                    dir("${env.WORKSPACE}/code"){
                        sh "cnpm install"
                        sh "npm run build"
                    }
                }
            }
        }
        
        stage('deploy') {
            steps {
                script {
                    dir("${env.WORKSPACE}/code/dist"){
                        def appName = "jp-employment-portal"
                        def host = "121.37.187.149"
                        sh "tar -czvf ${appName}.tar.gz ${appName}"
                        
                        withCredentials([usernamePassword(credentialsId: host, 
                                          passwordVariable: 'pwd', usernameVariable: 'userName')]) {
                            def sshServer = [:]
                            
                            sshServer.name = 'huawei server'
                            sshServer.host = host
                            
                            sshServer.user = userName
                            sshServer.password = pwd
                            
                            sshServer.allowAnyHosts= true

                            def folder = "/opt/websites";
                            sshPut remote: sshServer, from: appName + '.tar.gz', into: folder
                            sshCommand remote: sshServer, command: "rm -rf ${folder}/${appName}"
                            sshCommand remote: sshServer, command: "tar -zxvf ${folder}/${appName}.tar.gz -C ${folder}"
                        }
                    }
                }
            }
        }
    }
}
