def prNumber = BRANCH_NAME.tokenize("PR-")[0]
def runTestPath = "BenchmarkSetup/test/run_tests.sh"
def pattern = "[a-zA-Z0-9]+?.jl"
def repoName = (CHANGE_URL =~ pattern)[0]
def token = repoName.tokenize(".")[0]
pipeline {
  agent any
  options {
    skipDefaultCheckout false
  }
  triggers {
    GenericTrigger(
     genericVariables: [
        [
            key: 'org',
            value: '$.organization.login',
            expressionType: 'JSONPath', //Optional, defaults to JSONPath
            regexpFilter: '', //Optional, defaults to empty string
            defaultValue: '' //Optional, defaults to empty string
        ],
        [
            key: 'pullrequest',
            value: '$.pull_request.number',
            expressionType: 'JSONPath', //Optional, defaults to JSONPath
            regexpFilter: '', //Optional, defaults to empty string
            defaultValue: '$prNumber' //Optional, defaults to empty string
        ],
        [
            key: 'repo',
            value: '$.repository.name',
            expressionType: 'JSONPath', //Optional, defaults to JSONPath
            regexpFilter: '', //Optional, defaults to empty string
            defaultValue: '' //Optional, defaults to empty string
        ]
     ],

     causeString: 'Triggered on pullrequest update/creation',

     token: "$token",

     printContributedVariables: true,
     printPostContent: true,

     silentResponse: false,

     regexpFilterText: '$pullrequest',
     regexpFilterExpression: prNumber
    )
  }
  stages {
    stage('clone Setup') {
      when {
        expression { env.repo && env.org && env.pullrequest  }
      }
      steps {
        sh "git clone ${JENKINS_SETUP_URL} || true"
      }
    }
    stage('run tests') {
      when {
        expression { env.repo && env.org && env.pullrequest }
      }
      steps {
        script {
          if (fileExists('test/run_tests.sh')) {
            runTestPath = 'test/run_tests.sh';
          }
        }
        sh "chmod +x ${runTestPath}"
        sh "mkdir -p $HOME/tests/${org}/${repo}"
        sh "qsub -N ${repo}_${pullrequest}_test -V -cwd -e $HOME/tests/${org}/${repo}/${pullrequest}_${BUILD_NUMBER}_error.log ${runTestPath}"
      }
    }
  }
  post {
    success {
      echo "SUCCESS!"  
    }
    cleanup {
      sh 'printenv'
    }
  }
}
