#!/usr/bin/env groovy
/**
 *  Copyright 2021 Hewlett Packard Enterprise Development Company, L.P.
 */
library 'hpe-jenkins-libs'

// create (or update) the job input parameters
deriveJobParams(name:"build-job")

pipeline {
    /**
     * These env variables depend on the software component
     */
    environment {
        GITLAB_URL="git@gitlab.troof.io:data-pi-platform/hoang-gia/dap-pattern-search-standalone.git"
        GITLAB_BRANCH="master"
        IMAGE="ecorridor/iai/iai-openapi"
        LATEST_TAG="latest"
        DOCKER_FILE="docker/Dockerfile"
        DEPLOY_JOB="iai-openapi-deploy"
        DEPLOY_ENV_DEFAULT="dev"
    }
    options {
        copyArtifactPermission('/ECORRIDOR/IAI/iai-openapi-security')
        timeout(time: 1, unit: 'HOURS')
        buildDiscarder(logRotator(numToKeepStr: '100'))
        gitLabConnection('dev-gitlab')
    }
    agent none
    triggers {
        gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: 'All')
    }
    post {
        failure {
            updateGitlabCommitStatus name: 'build', state: 'failed'
        }
        success {
            updateGitlabCommitStatus name: 'build', state: 'success'
        }
    }
    stages {
        stage('Checkout Code') {
            agent {
               label 'docker'
            }
            steps {
               git url: "$GITLAB_URL",
                   branch: "$GITLAB_BRANCH",
                   credentialsId: 'user-jenkins-gitlab-ro-ssh'
            }
        }
        stage('Manage Container') {
             agent {
                     label 'docker'
             }
             steps {
                     manageContainer(name:"-manage container-")
             }
        }
        // this calls the deploy job
        stage('Call Deploy Job') {
           steps {
              build job: "${DEPLOY_JOB}", parameters: [string(name: 'GITLAB_URL', value: "${GITLAB_URL}"), string(name: 'PRJ_ENV', value: "${DEPLOY_ENV_DEFAULT}"), string(name: 'PRJ_IMAGE_TAG', value: "${LATEST_TAG}")]
           }
        }
        // archive artifacts for other pipelines
        stage('Archive Artifacts') {
            agent {
                label 'docker'
            }
            steps {
                archiveArtifacts artifacts: '**/*', followSymlinks: false, onlyIfSuccessful: true
            }
        }
    }
}
