#!/usr/bin/env groovy

import jenkins.model.*
def instance = Jenkins.getInstance()

def Jenkinsfile(name) {
    def script = """
def Jenkinsfile

node('workflow') {
   stage 'Load system-${name}'
   try {
       checkout([
           \$class: 'GitSCM',
           branches: [[name: "origin/pull/\${GITHUB_PR_NUMBER}/head"]],
           userRemoteConfigs: [[
               credentialsId: 'cf670269-124d-4f18-bcd8-d22fbcb29565',
               name: 'origin',
               refspec: "+refs/pull/\${GITHUB_PR_NUMBER}/head:refs/remotes/origin/pull/\${GITHUB_PR_NUMBER}/head",
               url: 'git@github.com:3scale/system.git'
            ]]
       ])
       branch = GITHUB_PR_SOURCE_BRANCH
   } catch (e) {
       git branch: branch, credentialsId: 'cf670269-124d-4f18-bcd8-d22fbcb29565', url: 'git@github.com:3scale/system.git'
   }

    sh('git rev-parse HEAD > GIT_COMMIT')
    env.GIT_COMMIT=readFile('GIT_COMMIT').trim()
    sh 'env'

    Jenkinsfile = load 'system-${name}.groovy'
    echo "Loaded system-${name}.groovy"
}

echo "Finished checkout of system-${name}.groovy"

Jenkinsfile()
"""
    def scriptApproval = Jenkins.instance.getExtensionList('org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval')[0]
    scriptApproval.approveScript(scriptApproval.hash(script, 'groovy'))
    return script
}


pipelineJob('system-pipeline') {
    quietPeriod(30)

    scm {
        // this sets the project name, but we can't set the custom context name
        // https://issues.jenkins-ci.org/browse/JENKINS-33651
        github('3scale/system')
    }

    properties {
        // githubProjectUrl('https://github.com/3scale/system')
        rebuild {
            autoRebuild()
        }
    }

    logRotator {
        artifactDaysToKeep(30)
        daysToKeep(30)
    }

    parameters {
       booleanParam('PERCY_ENABLE', true, 'Enable Percy for this build?')
       booleanParam('CACHE', true, 'Enable build cache?')
       booleanParam('ARCHIVE_LOGS', false, 'Enable archiving logs')
       stringParam('branch', 'master', 'Branch to build when triggered manually')
    }

    triggers {
        onPullRequest {
            setPreStatus()
            cancelQueued()
            abortRunning()

            cron('H/20 * * * *')
            // This needs https://github.com/jenkinsci/github-integration-plugin/pull/62 merged & released
            mode {
                heavyHooksCron()
            }
            events {
                labelAdded("jenkins")
                skipLabelNotExists("jenkins")
                commit()
            }
        }
    }

    definition {
        cps {
            script(Jenkinsfile('pipeline'))
        }
    }
}



pipelineJob('system-percy') {
    quietPeriod(60)

    scm {
        // this sets the project name, but we can't set the custom context name
        // https://issues.jenkins-ci.org/browse/JENKINS-33651
        github('3scale/system')
    }

    properties {
        // githubProjectUrl('https://github.com/3scale/system')
        rebuild {
            autoRebuild()
        }
    }

    parameters {
       booleanParam('CACHE', true, 'Enable build cache?')
       stringParam('branch', 'master', 'Branch to build when triggered manually')
    }

    triggers {
        cron('@daily')
        scm('@hourly')

        onPullRequest {
            cancelQueued()

            cron('H * * * *')

            mode {
                heavyHooksCron()
            }

            events {
                labelAdded("percy")
                skipLabelNotExists("percy")
                commit()
            }
        }
    }

    definition {
        cps {
            script(Jenkinsfile('percy'))
        }
    }
}


freeStyleJob('system') {
    scm {
        git {
            remote {
                github('3scale/system', 'ssh')
                credentials('cf670269-124d-4f18-bcd8-d22fbcb29565') // bender
            }
            branch('master')
        }
    }

    throttleConcurrentBuilds {
        maxTotal(1)
    }

    properties {
        rebuild {
            autoRebuild()
        }
    }
    triggers {
        githubPush()
        scm 'H/10 * * * *'
        cron "@daily\nH 22-23/3 * * *\nH 0-7/3 * * *"
    }

    wrappers {
        colorizeOutput()
        timeout {
            abortBuild()
            absolute(60)
        }
    }

    publishers {
        aggregateDownstreamTestResults('system-pipeline', true)
        githubCommitNotifier()
        slackNotifier {
            room('system')
            notifyAborted(true)
            notifyFailure(true)
            notifyNotBuilt(false)
            notifyUnstable(true)
            notifyBackToNormal(true)
            notifySuccess(true)
            notifyRepeatedFailure(false)
            startNotification(true)
            includeTestSummary(false)
            includeCustomMessage(false)
            customMessage(null)
            sendAs(null)
            commitInfoChoice('NONE')
            teamDomain(null)
            authToken(null)
            authTokenCredentialId(null)
        }
        retryBuild {
            rerunIfUnstable()
            retryLimit(30)
            progressiveDelay(30, 900)
        }
    }

    steps {
        downstreamParameterized {
            trigger('system-pipeline') {
                block {
                    buildStepFailure('FAILURE')
                    failure('FAILURE')
                    unstable('UNSTABLE')
                }

                parameters {
                    gitRevision()
                    currentBuild()
                    predefinedProp('PERCY_ENABLE', '${PERCY_ENABLE}')
                    predefinedProp('branch', 'master')
                }

            }
        }
    }
}
