// GUARDiA ITSM — 배포 전용 파이프라인 (빌드 없음)
// 기존 아티팩트를 지정하여 배포만 수행한다.

pipeline {
    agent any

    parameters {
        string(name: 'ITSM_SESSION_ID',  defaultValue: '', description: 'GUARDiA 바이브 세션 ID')
        string(name: 'ITSM_SR_ID',       defaultValue: '', description: '연결된 SR ID')
        choice(name: 'DEPLOY_ENV',       choices: ['dev', 'stg', 'prd'], description: '배포 환경')
        string(name: 'TARGET_SERVER',    defaultValue: '', description: '배포 대상 서버명')
        string(name: 'ARTIFACT_BUILD',   defaultValue: '', description: '아티팩트 소스 빌드 번호 (비워두면 lastSuccessfulBuild)')
        string(name: 'ARTIFACT_JOB',     defaultValue: '', description: '아티팩트 소스 Job 이름')
        string(name: 'WAS_TYPE',         defaultValue: 'tomcat', description: 'WAS 종류 (tomcat/jboss/jeus/nodejs)')
    }

    environment {
        SCRIPTS_ROOT  = "${WORKSPACE}/cicd/scripts/pipeline"
        NOTIFY_SCRIPT = "${WORKSPACE}/cicd/scripts/notify/itsm_callback.sh"
    }

    options {
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30'))
    }

    stages {
        stage('Resolve Artifact') {
            steps {
                script {
                    def buildNum = params.ARTIFACT_BUILD ?: 'lastSuccessfulBuild'
                    def jobName  = params.ARTIFACT_JOB  ?: env.JOB_NAME

                    echo "아티팩트 소스: ${jobName} #${buildNum}"

                    // Jenkins 아티팩트 복사
                    copyArtifacts(
                        projectName: jobName,
                        selector: buildNum == 'lastSuccessfulBuild'
                            ? lastSuccessful()
                            : specific(buildNum),
                        target: 'artifacts/',
                        flatten: true,
                        optional: false
                    )

                    def files = sh(script: "ls artifacts/", returnStdout: true).trim()
                    echo "다운로드된 아티팩트:\n${files}"
                }
            }
        }

        stage('Production Approval') {
            when {
                expression { return params.DEPLOY_ENV == 'prd' }
            }
            steps {
                sh "bash ${NOTIFY_SCRIPT} PENDING_APPROVAL '운영 배포 승인 대기'"
                timeout(time: 30, unit: 'MINUTES') {
                    input message: "운영 배포를 승인하시겠습니까?\n소스: ${params.ARTIFACT_JOB} #${params.ARTIFACT_BUILD}",
                          ok: "승인"
                }
            }
        }

        stage('Deploy') {
            steps {
                sh "bash ${NOTIFY_SCRIPT} DEPLOYING '배포 시작'"
                withCredentials([sshUserPrivateKey(
                    credentialsId: "ssh-${params.TARGET_SERVER}",
                    keyFileVariable: 'SSH_KEY',
                    usernameVariable: 'SSH_USER'
                )]) {
                    sh """
                        ARTIFACT=\$(ls artifacts/*.jar artifacts/*.war artifacts/*.tar.gz 2>/dev/null | head -1)
                        bash ${SCRIPTS_ROOT}/deploy.sh \
                            --server   "${params.TARGET_SERVER}" \
                            --env      "${params.DEPLOY_ENV}" \
                            --ssh-key  "\${SSH_KEY}" \
                            --ssh-user "\${SSH_USER}" \
                            --artifact "\${ARTIFACT}"
                    """
                }
            }
        }

        stage('WAS Restart') {
            steps {
                withCredentials([sshUserPrivateKey(
                    credentialsId: "ssh-${params.TARGET_SERVER}",
                    keyFileVariable: 'SSH_KEY',
                    usernameVariable: 'SSH_USER'
                )]) {
                    sh """
                        bash ${SCRIPTS_ROOT}/was_restart.sh \
                            --server   "${params.TARGET_SERVER}" \
                            --ssh-key  "${SSH_KEY}" \
                            --ssh-user "${SSH_USER}" \
                            --was-type "${params.WAS_TYPE}"
                    """
                }
            }
        }

        stage('Health Check') {
            steps {
                retry(3) {
                    sh """
                        bash ${SCRIPTS_ROOT}/health_check.sh \
                            --url "${env.HEALTH_CHECK_URL ?: 'http://localhost:8080/health'}" \
                            --timeout 60
                    """
                }
            }
            post {
                failure {
                    sh "bash ${SCRIPTS_ROOT}/rollback.sh --server '${params.TARGET_SERVER}' --reason '헬스체크 실패' || true"
                }
            }
        }

        stage('ITSM Callback') {
            steps {
                sh "bash ${NOTIFY_SCRIPT} COMPLETED '배포 전용 파이프라인 완료'"
            }
        }
    }

    post {
        always { cleanWs() }
        failure {
            sh "bash ${NOTIFY_SCRIPT} FAILED '배포 실패' || true"
        }
    }
}
