/*
 * The build uses either public snapshots or branch-specific repositories on the Jenkins
 * build server as upstream repositories. Use the argument '-PuseJenkinsSnapshots=true'
 * to enable the Jenkins repositories. In this case the upstream branch for each upstream
 * repository is tried to auto-detect. When a job for the upstream repository exists with
 * the same name as the current branch, then this is taken. Next, the branch's tracking branch
 * name is tried, when configured. Last, 'master' is taken as fallback. The upstream branch
 * name can be explicitly overridden when the argument '-PupstreamBranch=<branch name>'
 * is set.
 */

if (!hasProperty('JENKINS_URL')) {
  ext.JENKINS_URL = 'https://ci.eclipse.org/xtext'
}

ext.MVN_REPOPATH = 'lastStableBuild/artifact/build/maven-repository/'


def jenkinsPipelineRepo = { jobName, branch ->
  def upstreamBranch = upstream_branch(jobName, branch)
  def upstreamRepo = "$JENKINS_URL/job/$jobName/job/$upstreamBranch/$MVN_REPOPATH"
  logger.debug "[$jobName] Using upstream repository $upstreamRepo"
  return upstreamRepo
}

repositories {
  mavenCentral()
  if (findProperty('useJenkinsSnapshots') == 'true') {
    maven { url "$JENKINS_URL/job/lsp4j/$MVN_REPOPATH" }
    maven { url jenkinsPipelineRepo('xtext-lib','autodetect') }
    maven { url jenkinsPipelineRepo('xtext-core','autodetect') }
    maven { url jenkinsPipelineRepo('xtext-extras','autodetect') }
    maven { url jenkinsPipelineRepo('xtext-eclipse','autodetect') }
  } else {
    mavenLocal()
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
  }
}

/**
 * Retrieves the name of the upstream branch to use for given job. This will be
 * one of the following:
 * - the value of property 'upstreamBranch', when explicitly set
 * - when argument 'branch' is not 'autodetect', then value of 'branch'
 * - the name of the current branch, when a job exists on Jenkins for the upstream repository also
 * - the name of the tracking branch, when a tracking branch is configured and a job exists on Jenkins for the tracked branch name
 *   on the upstream repository
 * - 'master' as fallback
 */
def upstream_branch (jobName, branch) {
  if (hasProperty('upstreamBranch')) {
    logger.info "$project.name $jobName] Using upstream branch $upstreamBranch (upstreamBranch property is set)"
    return ext.upstreamBranch
  }
  if (branch != 'autodetect') {
    logger.info "$project.name $jobName] Using upstream branch $branch (explicitly set)"
    return branch
  }
  def branch_candidates = []
  if (System.env['BRANCH_NAME'] != null) {
    branch_candidates << System.env['BRANCH_NAME']
  }
  branch_candidates << grgit.branch.current().name
  if (grgit.branch.current().trackingBranch != null) {
    branch_candidates << grgit.branch.current().trackingBranch.name
  }
  
  def selectedBranch = branch_candidates.find { candidate -> url_exists(new URL("$JENKINS_URL/job/$jobName/job/$candidate/$MVN_REPOPATH")) }
  if (selectedBranch == null) {
    // fallback
    selectedBranch = 'master'
  }
  logger.info "[$project.name $jobName] Using upstream branch $selectedBranch (autodetect)"
  return selectedBranch
}

/**
 * Checks an URL that it exists, i.e. no HTTP 404 for it
 */
def url_exists (URL url) {
  logger.debug ("check url $url")
  def code = url.openConnection().with {
    requestMethod = 'HEAD'
    connect()
    responseCode
  }
  if (code == 404) {
    logger.debug ("$url does not exist")
    return false
  }
  return true
}
