#!groovy

def repository = "registry.c.test-chamber-13.lan"
def repositoryCreds = "harbor-repository-creds"

def workspace
def dockerFile

def label = "kubernetes-${UUID.randomUUID().toString()}"
def templateName = "pipeline-worker"
pipeline {
    agent {
        kubernetes {
            yaml functions.podYaml(
                repo: repository,
                templateName: templateName,
                kaniko: true
            )
        }
    }

    stages {
        stage ('Initalize Jenkins') {
            steps {
                script {
                    workspace = pwd()
                    writeFile(file: workspace + "/test-chamber-13.lan.root.crt", text: functions.getCurrentRootCA())
                    writeFile(file: workspace + "/test-chamber-13.lan.ret.root.crt", text: functions.getRetiredRootCA())
                    dockerFile = """FROM ${repository}/dockerhub/library/php:apache

LABEL org.opencontainers.image.authors="The_Spider <spider@smoothnet.org>"
LABEL org.opencontainers.image.title="php-mysqli"
LABEL org.opencontainers.image.description="Docker container for php with mysqli served by apache"
LABEL org.opencontainers.image.base.name="docker.io/library/php:apache"

COPY test-chamber-13.lan.root.crt test-chamber-13.lan.ret.root.crt /usr/local/share/ca-certificates/

RUN apt-get update && \\
    apt-get upgrade -y && \\
    apt-get autoremove -y && \\
    apt-get clean && \\
    update-ca-certificates && \\
    rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/* && \\
    docker-php-ext-install mysqli
"""
                }
            }
        }

        stage ('Build & Push') {
            steps {
                container ('kaniko') {
                    script {
                        declarativeFunctions.buildContainerMultipleDestinations(
                            dockerFile: dockerFile,
                            repositoryAccess: [
                                [
                                    repository: repository,
                                    credentials: repositoryCreds
                                ],
                                [
                                    repository: "https://index.docker.io/v1/",
                                    credentials: "dockerhub-repository-creds"
                                ],
                            ],
                            destination: [
                                "index.docker.io/thespider/php-mysqli:latest",
                                "${repository}/library/php-mysqli:latest",
                            ]
                        )
                    }
                }
            }
        }
    }
}