def label = "jenkins-${UUID.randomUUID().toString()}"
def templateName = "pipeline-worker"

def repository = "registry.c.test-chamber-13.lan"
def kanikoImage = "${repository}/library/kaniko:latest"
def repositoryCreds = "harbor-repository-creds"

def steamCreds = "steam-credentials"
def steamToken = "steam-token"
def steamTokenName = "ssfn7445013141740368289"

podTemplate(
    label: label,
    name: templateName,
    yaml: functions.podYaml(
        repo: repository,
        templateName: templateName,
        kaniko: true,
        alpine: true
    )
) {
    node (label) {
        def workspace = pwd()

        stage ("Prepare Kaniko") {
            container ("kaniko") {
                withCredentials([usernameColonPassword(
                    credentialsId: repositoryCreds,
                    variable: "dCreds",
                )]) {
                    def dockerJSON = """{
                        "auths": {
                            "${repository}": {
                                "auth": "${dcreds.bytes.encodeBase64().toString()}"
                            }
                        }
                    }"""
                    sh """
                        set +x
                        echo '${dockerJSON}' > /kaniko/.docker/config.json
                    """
                }
            }
        }

        stage("Kaniko Build & Push") {
            container ("kaniko") {
                def dockerfile = """
FROM ${repository}/dockerhub/cm2network/steamcmd:latest

ARG STEAM_USER
ARG STEAM_PASS
ARG STEAM_TOKEN

EXPOSE 16261/udp
EXPOSE 27015/udp

COPY --chown=1000:1000 ./\${STEAM_TOKEN} /home/steam/Steam/\${STEAM_TOKEN}

RUN /home/steam/steamcmd/steamcmd.sh +quit && \\
    /home/steam/steamcmd/steamcmd.sh +force_install_dir /home/steam/ProjectZomboid +login "\${STEAM_USER}" "\${STEAM_PASS}" +app_update 380870 validate +quit && \\
    rm -f /home/steam/Steam/\${STEAM_TOKEN}

WORKDIR /home/steam/ProjectZomboid

ENTRYPOINT ["/bin/bash", "-c", "/home/steam/ProjectZomboid/start-server.sh"]
"""
                writeFile(file: workspace + "/Dockerfile", text: dockerfile)
                withCredentials([
                    usernamePassword(
                        credentialsId: steamCreds,
                        usernameVariable: "steamUser",
                        passwordVariable: "steamPass"
                    ),
                    file(
                        credentialsId: steamToken,
                        variable: "steamTokenFile"
                    )
                ]) {
                    sh "cp " + '${steamTokenFile}' + " ${workspace}/${steamTokenName}"
                    sh """
                            /kaniko/executor \\
                                --context "${workspace}" \\
                                -f "${workspace}/Dockerfile" \\
                                --destination "${repository}/library/projectzomboid-server:latest" \\
                                --single-snapshot \\
                                --build-arg STEAM_USER="${steamUser}" \\
                                --build-arg STEAM_PASS="${steamPass}" \\
                                --build-arg STEAM_TOKEN="${steamTokenName}"
                    """
                }
            }
        }

        functions.deletePod(
            kubeAuth: "rancher-admin-token",
            kubeURL: "https://rancher.test-chamber-13.lan/k8s/clusters/c-mc9cq",
            namespace: "game-servers",
            selector: "workload.user.cattle.io/workloadselector=apps.deployment-game-servers-project-zomboid"
        )
    }
}