/**
* Jenkinsfile 示例代码
* 拷贝使用要记得修改agent和steps内执行项目
*/
pipeline {
    agent none
    stages {
        // 生产
        // stage('prod build') {
        //     // 当分支为master的时候执行
        //     when {
        //         branch 'master'
        //         beforeAgent true // 设置 beforeAgent 为 true 来避免直接运行 docker 容器
        //     }

        //     // 自动构建项目根目录下的 Dockerfile 文件，并使用其为运行容器
        //     agent { dockerfile true } 

        //     // 一些额外的选项
        //     options {
        //         // 失败则重试三次
        //         retry(3)
        //     }
            
        //     steps {
        //         // 在容器中执行 shell
        //         sh 'composer'
        //         // 在jenkins输出中打印信息
        //         echo '一些有用的信息'
        //     }
        // }
       
        // 开发环境
        stage('main build') {
            when {
                branch 'main'
                beforeAgent true
            }

            // 在标签为 'test80' 的服务器上执行
            agent { label 'devPhp80' }
            // 复杂参数 docker
            // agent {
            //     docker {
            //         label 'test80' // 使用 label 为 test80 的节点为宿主机运行docker
            //         image 'php:7.4-cli' 
            //         args '-d -p 13333:8080 -d -w /usr/src/app -v $PWD:/usr/src/app' // 参数
            //     }
            // }

            steps {
                echo 'master step执行完了'
            }
        }
        //测试环境
        stage('test build') {
            when {
                branch 'test'
                beforeAgent true
            }

            // 在标签为 'test80' 的服务器上执行
            agent { label 'devPhp80' }
            // 复杂参数 docker
            // agent {
            //     docker {
            //         label 'test80' // 使用 label 为 test80 的节点为宿主机运行docker
            //         image 'php:7.4-cli' 
            //         args '-d -p 13333:8080 -d -w /usr/src/app -v $PWD:/usr/src/app' // 参数
            //     }
            // }

            steps {
                echo '拷贝后端测试环境变量'
                sh '''
                    cd api 
                    cp ./dotenv/.test.env .env
                    cd ..
                '''
                echo '拷贝后台测试环境变量'
                sh '''
                    cd h5 
                    cp ./dotenv/.test-on-server.env .env
                    cd ..
                '''
                echo '构建前端'
                echo 'test step执行完了'
            }
        }
        // 没有when也就是任意时候都会执行
        stage('after build') {
            agent any // 在任何可用的代理上执行流水线或阶段，没有多节点的情况下其实就是直接执行shell啦。。

            steps {
                echo '结束了Always excecute after other stages.'
            }
        }
    }
    // 根据执行结果执行
    post {
        // 失败
        failure {
            echo 'FAILURE MESSAGE'
        }
        // 成功
        success {
            echo 'SUCCESS MESSAGE'
        }
    }
}