import jetbrains.buildServer.configs.kotlin.v2018_1.*
import jetbrains.buildServer.configs.kotlin.v2018_1.buildFeatures.commitStatusPublisher
import jetbrains.buildServer.configs.kotlin.v2018_1.buildSteps.dockerCompose
import jetbrains.buildServer.configs.kotlin.v2018_1.buildSteps.exec
import jetbrains.buildServer.configs.kotlin.v2018_1.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2018_1.triggers.vcs

/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.

VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.

To debug settings scripts in command-line, run the

    mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate

command and attach your debugger to the port 8000.

To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/

version = "2018.1"

project {
    description = "Demo Project for Matterhorn"

    buildType(InitializeMyBuild)

    template(ProductionEnvironmentVariables)
    template(Build)
    template(Test)

    subProject(PullRequest)
    subProject(Master)
}

object InitializeMyBuild : BuildType({
    name = "Initialize My Build"

    params {
        param("git.branch.specification", """
            +:refs/tags/(release-*)
            +:refs/tags/(v*-hotfix)
            +:refs/tags/(*-test)
            +:refs/tags/(Windows/v*)
        """.trimIndent())

        param("git.tag.match", "")
    }

    vcs {
        root(DslContext.settingsRoot)

        cleanCheckout = true
        excludeDefaultBranchChanges = true
    }

    steps {
        script {
            scriptContent = """
                #!/usr/bin/env ruby
                
                if '%git.tag.match%'.empty?
                puts 'No matching to be done'
                else
                puts 'Matching against: %git.tag.match%'
                end
            """.trimIndent()
        }
    }
})

object Build : Template({
    name = "Build"

    maxRunningBuilds = 1

    params {
        param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true")
        param("git.branch.specification", """
            +:refs/tags/(release-*)
            +:refs/tags/(v*-hotfix)
            +:refs/tags/(Windows/v*)
        """.trimIndent())
    }

    vcs {
        root(DslContext.settingsRoot)

        cleanCheckout = true
        excludeDefaultBranchChanges = true
    }

    steps {
        exec {
            id = "RUNNER_110"
            path = "./run.rb"
        }
    }

    triggers {
        vcs {
            id = "vcsTrigger"
        }
    }
})

object ProductionEnvironmentVariables : Template({
    name = "Production Environment Variables"

    params {
        param("env.TestEnvVar", "123")
    }
})

object Test : Template({
    name = "Test"

    maxRunningBuilds = 1

    params {
        param("git.branch.specification", "")
    }

    vcs {
        root(DslContext.settingsRoot)

        cleanCheckout = true
        excludeDefaultBranchChanges = true
    }

    steps {
        exec {
            id = "RUNNER_110"
            path = "./test.rb"
        }
    }
})


object Master : Project({
    name = "master"

    buildType(Master_Build)
    buildType(Master_BuildAgain)

    template(Master_Test)
})

object Master_Build : BuildType({
    templates(Build, ProductionEnvironmentVariables)
    name = "Build"

    maxRunningBuilds = 0

    triggers {
        vcs {
            id = "vcsTrigger"
            branchFilter = """
                +:release-*
                +:refs/heads/master
            """.trimIndent()
        }
    }
})

object Master_BuildAgain : BuildType({
    templates(Build, ProductionEnvironmentVariables)
    name = "Build Again"

    maxRunningBuilds = 0

    vcs {
        buildDefaultBranch = false
    }

    triggers {
        vcs {
            id = "vcsTrigger"
            branchFilter = """
                +:v*
                +:release-*
                +:*-test
                +:Windows/v*
            """.trimIndent()
        }
    }

    dependencies {
        snapshot(InitializeMyBuild) {
            onDependencyCancel = FailureAction.CANCEL
        }
    }
})

object Master_Test : Template({
    name = "Test"
})


object PullRequest : Project({
    name = "pull-request"

    buildType(PullRequest_Build)
    buildType(PullRequest_Test)
    buildType(PullRequest_RunFullBuildSuite)

    template(PullRequest_Test2)
    buildTypesOrder = arrayListOf(PullRequest_RunFullBuildSuite, PullRequest_Build, PullRequest_Test)
})

object PullRequest_Build : BuildType({
    templates(Build)
    name = "Build"

    maxRunningBuilds = 2

    params {
        param("git.branch.specification", """
            +:refs/pull/(*)/head
            -:<default>
        """.trimIndent())
    }

    vcs {
        buildDefaultBranch = false
    }

    steps {
        script {
            name = "Test ruby script"
            id = "RUNNER_173"
            scriptContent = """
                #!/usr/bin/env ruby
                
                puts 'test'
            """.trimIndent()
        }
        dockerCompose {
            id = "RUNNER_311"
        }
        stepsOrder = arrayListOf("RUNNER_173", "RUNNER_110")
    }

    features {
        commitStatusPublisher {
            id = "BUILD_EXT_12"
            vcsRootExtId = "${DslContext.settingsRoot.id}"
            publisher = github {
                githubUrl = "https://git.xarth.tv/api/v3"
                authType = personalToken {
                    token = "credentialsJSON:06c8cbc2-4163-4856-a7b1-e768875cd57d"
                }
            }
        }
    }
})

object PullRequest_RunFullBuildSuite : BuildType({
    name = "Run Full Build Suite"

    type = BuildTypeSettings.Type.COMPOSITE
    maxRunningBuilds = 2

    params {
        param("git.branch.specification", "${PullRequest_Build.depParamRefs["git.branch.specification"]}")
    }

    vcs {
        root(DslContext.settingsRoot)

        buildDefaultBranch = false
        excludeDefaultBranchChanges = true
        showDependenciesChanges = true
    }

    triggers {
        vcs {
        }
    }

    dependencies {
        snapshot(PullRequest_Build) {
            reuseBuilds = ReuseBuilds.NO
            onDependencyCancel = FailureAction.ADD_PROBLEM
        }
        snapshot(PullRequest_Test) {
            reuseBuilds = ReuseBuilds.NO
            onDependencyCancel = FailureAction.ADD_PROBLEM
        }
    }
})

object PullRequest_Test : BuildType({
    templates(Test)
    name = "Test"

    maxRunningBuilds = 2

    params {
        param("git.branch.specification", """
            +:refs/pull/(*)/head
            -:<default>
        """.trimIndent())
    }

    vcs {
        buildDefaultBranch = false
    }

    features {
        commitStatusPublisher {
            id = "BUILD_EXT_15"
            vcsRootExtId = "${DslContext.settingsRoot.id}"
            publisher = github {
                githubUrl = "https://git.xarth.tv/api/v3"
                authType = personalToken {
                    token = "credentialsJSON:06c8cbc2-4163-4856-a7b1-e768875cd57d"
                }
            }
        }
    }
})

object PullRequest_Test2 : Template({
    name = "Test 2"
})
