import hudson.AbortException

def getGitlabToken() {
    def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        org.jenkinsci.plugins.plaincredentials.StringCredentials.class,
        jenkins.model.Jenkins.instance
    )

    def c = creds.findResult { it.id == "GITLAB_SECRET_TOKEN" ? it : null }

    if (c) {
        return c.secret.plainText
    } else {
        throw new AbortException("Could not locate Gitlab secret token")
    }
}

pipeline {
	agent { label "docker" }

	environment {
		DOCKER_IMAGE = "jointbyte/wordpatch"
		SVN_CREDS = credentials('creds-wordpress-svn-orfeasyours')
	}

	post {
		failure {
			updateGitlabCommitStatus name: "build", state: "failed"
		}

		success {
			updateGitlabCommitStatus name: "build", state: "success"
		}

		aborted {
			updateGitlabCommitStatus name: "build", state: "canceled"
		}
	}

	options {
		gitLabConnection("Gitlab Public")
		skipDefaultCheckout true
	}

	triggers {
		gitlab(
			triggerOnPush: true,
			triggerOnMergeRequest: true,
			triggerOpenMergeRequestOnPush: "both",
			triggerOnNoteRequest: true,
			noteRegex: "ci-retry",
			ciSkip: true,
			setBuildDescription: true,
			branchFilterType: "NameBasedFilter",
			includeBranchesSpec: "master",
			excludeBranchesSpec: "",
			secretToken: getGitlabToken()
		)
	}

	stages {
		stage("setup") {
			steps {
			    updateGitlabCommitStatus name: 'build', state: 'pending'

			    checkout scm

				script {
					GIT_COMMIT = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
					SHORT_COMMIT = GIT_COMMIT.take(6)
				}
			}
		}

		stage("build") {
			steps {
			    updateGitlabCommitStatus name: 'build', state: 'running'

				script {
					sh "docker build --no-cache -t $DOCKER_IMAGE:$SHORT_COMMIT ."
					builtDockerImg = docker.image("$DOCKER_IMAGE:$SHORT_COMMIT")
				}
			}
		}

		stage("commit") {
			when {
				environment name: "gitlabSourceBranch", value: "master"
				environment name: "gitlabTargetBranch", value: "master"
			}

			steps {
				script {
					sh "docker run --rm -e SVN_CREDS_USR -e SVN_CREDS_PSW $DOCKER_IMAGE:$SHORT_COMMIT commit"
				}
			}
		}
	}
}
