pipeline {
    agent any

    environment {
        DOCKER_IMAGE = 'caliverse/admintool-back-qa'
        DOCKER_TAG = '1.0.0'
        DOCKER_TAG_PRE = '1.0.0'
        FILE_NAME = 'admintool_back_qa.tar'
        DOCKER_NAME = 'admintool-back-qa'
        DOCKER_PORT = '23450'
        DOCKERFILE_NAME = 'Dockerfile.qa'
        META_FOLDER = 'metadata/*'
        REMOTE_META_FOLDER = 'admintool'
    }

    stages {
        stage('Gradle Build') {
            steps {
                script {
                    sh 'chmod +x gradlew'  //gradle 권한 설정
                    sh './gradlew clean build -x test -Pprofile=qa'     //빌드 test는 하지않는다
                }
            }
        }
        stage('Docker Image Build') {
            steps {
                script {
                    sh 'docker rmi $DOCKER_IMAGE:$DOCKER_TAG_PRE || true'   //이전 이미지 삭제
                    sh 'rm $FILE_NAME || true'   //이전 .tar 파일 삭제
                    sh 'docker build -f $DOCKERFILE_NAME -t $DOCKER_IMAGE:$DOCKER_TAG .'
                    echo 'Docker Image Create'
                    sh 'docker save -o $FILE_NAME $DOCKER_IMAGE:$DOCKER_TAG'
                    echo 'Docker Image > .tar File Create'
                }
            }
        }
        stage('MetaData Checkout'){
            steps{
                checkout([$class: 'SubversionSCM',
                    additionalCredentials: [],
                    excludedCommitMessages: '',
                    excludedRegions: '',
                    excludedRevprop: '',
                    excludedUsers: '',
                    filterChangelog: false,
                    ignoreDirPropChanges: false,
                    includedRegions: '',
                    locations: [
                        [
                            cancelProcessOnExternalsFail: true,
                            credentialsId: 'jenkins-build',
                            depthOption: 'infinity',
                            ignoreExternalsOption: true,
                            local: 'metadata',
                            remote: 'svn://10.20.20.9/branches/Stable/DataAssets/MS2/JSON@HEAD'
                        ]
                    ],
                    quietOperation: true,
                    workspaceUpdater: [$class: 'UpdateUpdater']
                ])
            }
        }
        stage('SSH Tunneling Start') {
            steps {
                script {
                    sh 'rm -rf ${WORKSPACE}/metadata/.svn'
                    sh 'rm -rf ${WORKSPACE}/metadata/QuestScript'
                    sh '/home/admintool/ssh-tunneling-qa.sh start'
                }
            }
        }
        stage('Transfer MeataData'){
            steps{
                sshPublisher(
                    publishers: [
                        sshPublisherDesc(
                            configName: 'qa-backend',
                            transfers: [
                                sshTransfer(
                                    sourceFiles: "${META_FOLDER}",
                                    remoteDirectory: "${REMOTE_META_FOLDER}",
                                    execCommand: """
                                        echo 'metadata Transfer Complete'
                                    """,
                                    execTimeout: 120000
                                )
                            ],
                            usePromotionTimestamp: false,
                            verbose: true
                        )
                    ]
                )
            }
        }
        stage('Transfer Docker Image') {
            steps {
                sshPublisher(
                    publishers: [
                        sshPublisherDesc(
                            configName: 'qa-backend',
                            transfers: [
                                sshTransfer(
                                    sourceFiles: "${FILE_NAME}",
                                    remoteDirectory: '',
                                    execCommand: """
                                        echo '.tar Transfer Complete'
                                    """,
                                    execTimeout: 120000
                                )
                            ],
                            usePromotionTimestamp: false,
                            verbose: true
                        )
                    ]
                )
            }
        }
        stage('Deploy to Remote'){
            steps{
                // aws command
                sshPublisher(
                    publishers: [
                        sshPublisherDesc(
                            configName: 'qa-backend',
                            transfers: [
                                sshTransfer(
                                    execCommand: """
                                        docker stop ${DOCKER_NAME} || true &&
                                        docker rm ${DOCKER_NAME} || true &&
                                        docker rmi ${DOCKER_IMAGE}:${DOCKER_TAG_PRE} || true &&
                                        docker load -i ${FILE_NAME} &&
                                        docker run -d \
                                            -p ${DOCKER_PORT}:${DOCKER_PORT} \
                                            --name ${DOCKER_NAME} \
                                            --restart=always \
                                            --log-opt max-size=10m \
                                            -e TZ=\${TZ:-Asia/Seoul} \
                                            -v ./admintool/log:/logs \
                                            -v ./admintool/upload:/upload \
                                            -v ./admintool/metadata:/metadata:ro,cached \
                                            ${DOCKER_IMAGE}:${DOCKER_TAG} &&
                                        rm ${FILE_NAME}
                                    """,
                                    execTimeout: 120000
                                )
                            ],
                            usePromotionTimestamp: false,
                            verbose: true
                        )
                    ]
                )
            }
        }
        stage('SSH Tunneling Stop') {
            steps {
                script {
                    sh 'rm -rf ${WORKSPACE}/metadata'
                    echo 'metadata Directory Remove'
                    sh '/home/admintool/ssh-tunneling-qa.sh stop; /home/admintool/ssh-tunneling-qa.sh status'
                }
            }
        }
    }
}