pipeline {
    agent any
    stages {
        stage('Tests and compiling binaries') {
            when {
                expression { env.CHANGE_BRANCH?.startsWith('feature/') }
            }
            steps {
                script {
                    echo "Building and running tests in Docker for feature branch..."
                    try {
                        def targetDirAmd = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/x86"
                        def targetDirRisc = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/riscv"
                        
                        sh "mkdir -p ${targetDir}"
                        
                        sh """
                        docker build --network=host -t e-monitor .
                        
                        docker run --name e-monitor --dns 8.8.8.8 --network=host e-monitor:latest
                        """
                        
                        sh "cp noxis-rs/settings.json ${targetDirAmd}"
                        sh "cp noxis-rs/settings.json ${targetDirRisc}"

                        sh "docker cp e-monitor:/usr/src/kii/target/x86_64-unknown-linux-gnu/release/noxis-cli ${targetDirAmd}"
                        sh "docker cp e-monitor:/usr/src/kii/target/x86_64-unknown-linux-gnu/release/noxis-rs ${targetDirAmd}"

                        sh "docker cp e-monitor:/usr/src/kii/target/riscv64gc-unknown-linux-gnu/release/noxis-cli ${targetDirRisc}"
                        sh "docker cp e-monitor:/usr/src/kii/target/riscv64gc-unknown-linux-gnu/release/noxis-rs ${targetDirRisc}"

                        sh "docker stop e-monitor && docker rm e-monitor"
                        echo "Tests passed successfully and binaries were extracted!"
                    } catch (Exception e) {
                        echo "Tests failed during Docker run."
                        error "Build failed at 'CI for feature' stage."
                    }
                }
            }
        }

        stage('Transfer Binaries') {
            when {
                expression { env.CHANGE_BRANCH?.startsWith('feature/') }
            }
            steps {
                script {
                    echo "Transferring binaries to remote machine..."
                    
                    withCredentials([usernamePassword(credentialsId: 'ift', passwordVariable: 'SSH_PASS', usernameVariable: 'SSH_USER')]) {
                        def targetDir = "${env.WORKSPACE}/${env.CHANGE_BRANCH}"
                        def remote = [:]
                        remote.name = "remote-server"
                        remote.host = "192.168.2.33"
                        remote.user = SSH_USER
                        remote.password = SSH_PASS
                        remote.allowAnyHosts = true
                        
                        sshPut remote: remote, from: "${targetDir}", into: "/home/user/deployments/"
                        echo "Binaries successfully transferred to remote machine."
                    }
                }
            }
        }

        stage('Merge Pull Request') {
            when {
                expression { env.CHANGE_ID != null }
            }
            steps {
                script {
                    echo "Attempting to merge PR ${env.CHANGE_ID} using credentials..."
                    withCredentials([usernamePassword(credentialsId: 'Jenkins creds', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_PASS')]) {
                        def prId = env.CHANGE_ID
                        sh """
                        curl -X POST \
                             -u "${GITEA_USER}:${GITEA_PASS}" \
                             -H "Content-Type: application/json" \
                             -d '{"Do":"merge"}' \
                             http://git.entcor/api/v1/repos/VladislavD/runner-rs/pulls/${prId}/merge
                        """
                        echo "PR ${prId} merged successfully!"
                    }
                }
            }
        }
    }
}
