#!/usr/bin/env groovy
import groovy.json.*
void printInfo(text) {
    ansiColor('xterm') { echo "\u001B[34m ${text}\u001B[0m" }
}
void printError(text) {
    ansiColor('xterm') { echo "\u001B[31m ${text}\u001B[0m" }
}

if (!params.RECONFIGURE) {
    properties([
            parameters([
                    string(name: 'JENKINS_NODE', defaultValue: 'efs', description: 'Метка агента Jenkins, на котором будет выполняться job', trim: true),
                    string(name: 'ARTIFACT_URL', defaultValue: '<ссылка на артефакт в репозитории артефактов>', description: 'Ссылка на артефакт', trim: true),
                    string(name: 'REPO_URL', defaultValue: 'https://works.ru/bitbucket-ci', description: 'Базовая ссылка на репозиторий', trim: true),
                    string(name: 'REPOSITORIES', defaultValue: '<ссылка на git репозиторий:хешкоммит', description: 'Репозитории к проверке', trim: true),
                    string(name: 'PROCESS_CODE', defaultValue: 'DefaultBuildScanningProcess', description: 'Процесс оркестратора', trim: true),
                    string(name: 'ORCHESTRATOR_URL', defaultValue: 'https://orchestrator-asoc-dev-1.apps.dap.devpub-01.solution.mycompany', description: 'Адрес оркестратора', trim: true),
                    string(name: 'RECONFIGURE', defaultValue: 'nope', description: 'Для реконфигурации job, параметр должен быть пустым', trim: true),
            ])
    ])
    currentBuild.displayName = 'Job reconfigured'
    currentBuild.result = 'SUCCESS'
    return this
}
def pattern = ~/\/(\w-\d+\.\d+\.\d+-\d+(_\w+)?)\/(\w+)-/
def matcher = params.ARTIFACT_URL =~ pattern
def distribVersion = matcher[0][1]
def distribId = matcher[0][3].toUpperCase()
def author = "tuz_mycompany_ci_asoc@mycompany.ru"
def processCode
// Периодический запрос на получение результата workflow
def workflowCheckStatus(distribId, processCode) {
    timeout(time: 30, unit: 'MINUTES') {
        while(true) {
            orchestratorReq = httpRequest(
                    acceptType: 'APPLICATION_JSON',
                    contentType: 'APPLICATION_JSON',
                    httpMode: 'GET',
                    ignoreSslErrors: true,
                    validResponseCodes: '100:500',
                    url: "${params.ORCHESTRATOR_URL}/v1/scanning/status/${distribId}/${processCode}"
            )
            if (orchestratorReq.status == 200 && orchestratorReq.content) {
                workflowResponse = readJSON (text: orchestratorReq.content)
                workflowStatus = workflowResponse["status"]
                if (workflowStatus in ["IN_PROGRESS"]) {
                    printInfo("'$processCode' status of '$distribId' is '$workflowStatus', retrying in 30 seconds...")
                    sleep(30)
                    continue
                } else if (workflowStatus in ["FAILED"]) {
                    workflowMessage = workflowResponse["status"]
                    printError("'$processCode' for '$distribId' has '$workflowStatus'. Message: '$workflowMessage'")
                    break
                } else if (workflowStatus == "COMPLETED") {
                    workflowMessage = workflowResponse["result"]
                    printInfo("'$processCode' for '$distribId' has succeeded.")
                    printInfo("Result - ${workflowMessage}")
                    break
                }
            }
        }
        return workflowResponse
    }
}
timestamps {
    node(params.JENKINS_NODE ?: 'имя агента по умолчанию') {
        cleanWs()
        if ([params.ARTIFACT_URL?.trim(), params.REPO_URL?.trim(), params.ORCHESTRATOR_URL?.trim(), params.REPOSITORIES?.trim(), params.PROCESS_CODE?.trim()].any { it in [null, 'null', ''] }) {
            error("Один или несколько обязательных параметров не заданы")
        }
        stage("Check component") {
            processCode = params.PROCESS_CODE
            def query = [
                    "buildPath":"${params.ARTIFACT_URL}",
                    "processCode": "${processCode}",
                    "repositories": []
            ]
            def repos = params.REPOSITORIES.tokenize(';')
            repos.each {
                def repo = it.tokenize(',')
                def element = [
                        "uri": "${params.REPO_URL}/scm/${repo[0]}.git",
                        "branch": "${repo[1]}",
                        "hash": "${repo[2]}"
                ]
                query.repositories << element
            }
            orchestratorReq = httpRequest(
                    acceptType: 'APPLICATION_JSON',
                    contentType: 'APPLICATION_JSON',
                    httpMode: 'POST',
                    url: "${params.ORCHESTRATOR_URL}/v1/scanning/build/${distribId}",
                    ignoreSslErrors: true,
                    validResponseCodes: '100:500',
                    requestBody: JsonOutput.toJson(query)
            )
            if (orchestratorReq.status == 200) {
                printInfo("Сканирование успешно запущено, отслеживаем статус..")
                //                orchestratorResponse = readJSON (text: orchestratorReq.content)
                workflowCheckStatus(distribId, processCode)
            } else {
                def errMsg = (orchestratorReq.content) ? readJSON (text: orchestratorReq.content) : "Unknown error, server returns nothing."
                printError("Ошибка: ${errMsg}")
                error("Unable to create scan.")
            }
        }
    }
}
