#!/usr/bin/env groovy
// DOCKER_REG_URL needs to be defined on jenkins server (manage jenkins -> global settings)
// github-token needs to be defined on jenkins server (manage jenkins -> global credentials  secret text with id="github-token")
env.DOCKER_IMAGE_TAG="$DOCKER_REG_URL/" + "$JOB_NAME".split("/")[1].toLowerCase() + "/" + "$BRANCH_NAME".replaceAll("[^a-zA-Z0-9]", "_").toLowerCase()  + ":$BUILD_NUMBER"
node {

    def app

    properties([

        disableConcurrentBuilds(),
        buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10'))

    ])

    stage('Clone repository') {

        checkout scm

    }

    stage('Merge master') {

        // in project git settings on jenkins activate "Specific ref specs" and set it to "+refs/heads/*:refs/remotes/@{remote}/*"

        if (env.BRANCH_NAME == 'master') {

            echo "skip master merge on master"

        } else {

            sh "git config user.email backend@juwelo.de"
            sh "git config user.name Jenkins"
            sh "git merge --no-commit origin/master"

        }
    }

    stage('Build image') {

        withCredentials([string(credentialsId: 'github-token', variable: 'GIT_TOKEN')]) {
            sh "docker build --tag $DOCKER_IMAGE_TAG --target JFS_RUN --build-arg GIT_TOKEN=$GIT_TOKEN ."
        }
    }

    stage('Tests') {

        withCredentials([string(credentialsId: 'github-token', variable: 'GIT_TOKEN')]) {
            sh "docker build --target JFS_TEST --build-arg GIT_TOKEN=$GIT_TOKEN ."
        }
    }

    stage('Upload image') {

        sh "docker push $DOCKER_IMAGE_TAG"

    }

    stage('cleanup image') {

        sh "docker rmi --force $DOCKER_IMAGE_TAG"

    }
}
