pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', credentialsId: 'gitea', url: 'https://git.codeam.io/Julian/tlw-database-tool.git'
            }
        }
        stage('Build') {
            steps {
                script {
                    String jdkPath = tool name: 'OpenJDK19', type: 'jdk'
                    withCredentials([usernamePassword(credentialsId: 'aws', passwordVariable: 'AWS_SECRET_KEY', usernameVariable: 'AWS_ACCESS_KEY_ID')]) {
                        withEnv(["JAVA_HOME=${jdkPath}/jdk-19.0.2", "AWS_SECRET_KEY=${AWS_SECRET_KEY}", "AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}"]) {
                            sh returnStdout: false, script: "./gradlew build -x test"
                        }
                    }
                }
            }
        }
        stage('Archive') {
            steps {
                archiveArtifacts artifacts: 'build/libs/tlw-database-tool-1.0.jar', followSymlinks: false
            }
        }
        stage('Trigger') {
            steps {
                build wait: false, job: 'TippligaUpdater2023'
                build wait: false, job: 'WTLPokalUpdater2023'
            }
        }
    }
    post {
        always {
            deleteDir()
        }
        failure {
            telegramSendManual("Build failed!\n${env.BUILD_URL}console")
        }
    }
}

private String clean(String orig) {
    orig = orig.replace("\n\n", "\n")
    while(orig.indexOf(" [main] INFO  de.jeyp91.App - ") > 0) {
        int index = orig.indexOf(" [main] INFO  de.jeyp91.App - ")
        String newString = orig.substring(0, index-12) + orig.substring(index+30, orig.size())
        orig = newString
    }
    return orig
}

def telegramSendManual(String text) {
    def encodedMessage = URLEncoder.encode(text, "UTF-8")
    println encodedMessage
    httpRequest(
        httpMode: 'GET',
        contentType: 'APPLICATION_JSON',
        responseHandle: 'NONE',
        url: "https://api.telegram.org/bot1298223079:AAEplcQpfzFG59qNYAYuSbJKtB9HMXCCE_U/sendMessage?text=$encodedMessage&chat_id=459231986&disable_web_page_preview=true",
        wrapAsMultipart: false,
        consoleLogResponseBody: true
    )
    sleep 1
}