/*
Required plugins in Jenkins:
- Pipeline Utility Steps
- Docker Pipeline
*/

def app_version
def app_build
def url_download
def app_filename
def docker_tag
def docker_tag_latest

pipeline {
    agent any

    environment {
        URL_BASE = 'https://download.geysermc.org/v2/projects/geyser/versions'
        URL_BUILD_INFOS = "${URL_BASE}/latest/builds/latest"

        DOCKER_TAG_BASE = 'cr.pandacube.fr/geyser'
        DOCKER_REGISTRY_URL = 'https://cr.pandacube.fr'
        DOCKER_REGISTRY_CREDENTIALS = 'cr-pandacube-credentials'
    }

    stages {

        stage('Get build data') {
            steps {
                sh "curl -L -s '$URL_BUILD_INFOS' -o build_infos.json"
                script {
                    def build_infos = readJSON file: 'build_infos.json'

                    app_version = build_infos.version
                    app_build = build_infos.build
                    url_download = "${URL_BASE}/${app_version}/builds/${app_build}/downloads/standalone"
                    app_filename = "Geyser-${app_version}-${app_build}.jar"

                    docker_tag = "${DOCKER_TAG_BASE}:${app_version}-${app_build}"
                    docker_tag_latest = "${DOCKER_TAG_BASE}:latest"
                }
                echo "Geyser version ${app_version} build #${app_build}"
            }
        }

        stage('Download jar') {
            steps {
                sh "curl -L -o '$app_filename' '$url_download'"
            }
        }

        stage('Build Docker image') {
            steps {
                script {
                    docker.build(docker_tag, "--build-arg RUNNABLE_JAR=$app_filename .")
                }
                sh "docker tag ${docker_tag} ${docker_tag_latest}"
            }
        }

        stage('Push Docker image') {
            steps {
                script {
                    docker.withRegistry(DOCKER_REGISTRY_URL, DOCKER_REGISTRY_CREDENTIALS) {
                        docker.image(docker_tag).push()
                        docker.image(docker_tag_latest).push()
                    }
                }
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}