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: 'OpenJDK22', type: 'jdk'
                    withCredentials([
                        usernamePassword(credentialsId: 'aws', usernameVariable: 'AWS_ACCESS_KEY_ID', passwordVariable: 'AWS_SECRET_ACCESS_KEY'),
                        usernamePassword(credentialsId: 'forum_database', usernameVariable: 'TLW_DATABASE_USERNAME', passwordVariable: 'TLW_DATABASE_PASSWORD'),
                        usernamePassword(credentialsId: 'forum_user', usernameVariable: 'FORUM_USERNAME', passwordVariable: 'FORUM_PASSWORD')
                    ]) {
                        withEnv([
                            "JAVA_HOME=${jdkPath}/jdk-22.0.2"
                        ]) {
                            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 {
                echo 'Trigger jobs'
                build wait: false, job: 'TippligaUpdater'
                build wait: false, job: 'WTLPokalUpdater'
                build wait: false, job: 'SupercupUpdater'
                // build wait: false, job: 'RelegationUpdater'
                // build wait: false, job: 'LigaCupUpdater'
            }
        }
    }
    post {
        always {
            deleteDir()
        }
        failure {
            telegramSendManual("Build failed!\n${env.BUILD_URL}console")
        }
    }
}

private ArrayList<String> clean(ArrayList<String> orig) {
    ArrayList<String> cleaned = new ArrayList<String>()
    orig.each{line ->
        if(line.indexOf(" [main] INFO de.jeyp91 - ") >= 0) {
            line = line.substring(20, line.size())
        }

        if(line.indexOf(" [main] ERROR de.jeyp91") >= 0) {
            line = line.substring(20, line.size())
        }
        cleaned.add(line)
    }
    return cleaned.unique()
}

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
}