pipeline {
    agent any

    parameters {
        string(
                name: 'BRANCH',
                defaultValue: 'main',
                description: 'Ветка для деплоя легальной панели'
        )
        string(
                name: 'PORT',
                defaultValue: '2997',
                description: 'Порт для запуска экземпляра'
        )
    }

    stages {
        stage('Git pull') {
            steps {
                script {
                    checkout([
                            $class: 'GitSCM',
                            branches: [[name: params.BRANCH]],
                            userRemoteConfigs: [[
                                                        url: 'https://code.3err0.ru/frontdev/no-copy-legal-panel-frontend.git',
                                                        credentialsId: 'nx-jen'
                                                ]]
                    ])
                }
            }
        }

        stage('Stop old') {
            steps {
                script {
                    withCredentials([
                            usernamePassword(
                                    credentialsId: 'server-root-password',
                                    usernameVariable: 'SSH_USER',
                                    passwordVariable: 'SSH_PASS'
                            )
                    ]) {
                        sh """
                    sshpass -p '$SSH_PASS' ssh $SSH_USER@92.242.61.23 "
                        docker stop no-copy-legal-panel-${params.PORT} 2>/dev/null || true
                        docker rm no-copy-legal-panel-${params.PORT} 2>/dev/null || true
                        mkdir -p /opt/deployments/legal-panel/${params.BRANCH}-${params.PORT}
                        rm -rf /opt/deployments/legal-panel/${params.BRANCH}-${params.PORT}/*
                    "
                """
                    }
                }
            }
        }

        stage('Copy to server') {
            steps {
                script {
                    withCredentials([
                            usernamePassword(
                                    credentialsId: 'server-root-password',
                                    usernameVariable: 'SSH_USER',
                                    passwordVariable: 'SSH_PASS'
                            )
                    ]) {
                        sh """
                    sshpass -p '$SSH_PASS' scp -r ./* $SSH_USER@92.242.61.23:/opt/deployments/legal-panel/${params.BRANCH}-${params.PORT}/
                """
                    }
                }
            }
        }

        stage('Build on server') {
            steps {
                script {
                    withCredentials([
                            usernamePassword(
                                    credentialsId: 'server-root-password',
                                    usernameVariable: 'SSH_USER',
                                    passwordVariable: 'SSH_PASS'
                            )
                    ]) {
                        sh """
                        sshpass -p '$SSH_PASS' ssh $SSH_USER@92.242.61.23 "
                        cd /opt/deployments/legal-panel/${params.BRANCH}-${params.PORT}
                        docker build -t no-copy-legal-panel:${params.BRANCH}-${params.PORT} .
                    "
                """
                    }
                }
            }
        }

        stage('Start on server') {
            steps {
                script {
                    withCredentials([
                            usernamePassword(
                                    credentialsId: 'server-root-password',
                                    usernameVariable: 'SSH_USER',
                                    passwordVariable: 'SSH_PASS'
                            )
                    ]) {
                        sh """
                    sshpass -p '$SSH_PASS' ssh $SSH_USER@92.242.61.23 "
                        docker run -d \\
                            --name no-copy-legal-panel-${params.PORT} \\
                            --restart unless-stopped \\
                            --network app-network \\
                            -p ${params.PORT}:2997 \\
                            no-copy-legal-panel:${params.BRANCH}-${params.PORT}
                        sleep 5
                        docker ps --filter name=no-copy-legal-panel-${params.PORT}
                    "
                """
                    }
                }
            }
        }

        stage('Check status') {
            steps {
                script {
                    withCredentials([
                            usernamePassword(
                                    credentialsId: 'server-root-password',
                                    usernameVariable: 'SSH_USER',
                                    passwordVariable: 'SSH_PASS'
                            )
                    ]) {
                        sh """
                    sshpass -p '$SSH_PASS' ssh $SSH_USER@92.242.61.23 "
                        if docker ps --format '{{.Names}}' | grep -q 'no-copy-legal-panel-${params.PORT}'; then
                            HTTP_CODE=\$(curl -s -o /dev/null -w '%{http_code}' http://localhost:${params.PORT} 2>/dev/null || echo '000')
                            echo 'Legal panel available on http://92.242.61.23:${params.PORT}'
                        else
                            exit 1
                        fi
                    "
                """
                    }
                }
            }
        }
    }

    post {
        success {
            echo "Legal panel ${params.BRANCH} deployed on port ${params.PORT}"
        }
        failure {
            echo "Deployment failed"
        }
    }
}