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

def workspace
def latestTag
def outputFile

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

pipeline {
    agent {
        kubernetes{
            yaml functions.podYaml(
                repo: repository,
                templateName: templateName,
                alpine: true,
                [
                    [
                        name: "node",
                        path: "${repository}/dockerhub/library/node:20.9.0",
                        command: "/bin/bash"
                    ]
                ]
            )
        }
    }

    stages {
        stage ('Initalize Jenkins') {
            steps {
                script {
                    workspace = pwd()
                }
            }
        }

        stage ('Get latest Tag') {
            steps {
                container ('alpine') {
                    script {
                        sh """
                            if ! command -v curl &> /dev/null; then
                                apk add --no-cache curl
                            fi
                            if ! command -v jq &> /dev/null; then
                                apk add --no-cache jq
                            fi
                        """
                        latestTag = sh (
                            script: """
                                curl \
                                    --location \
                                    --silent \
                                    --fail \
                                    --request GET \
                                    --url https://api.github.com/repos/signalapp/Signal-Desktop/releases/latest | \
                                jq -r 'select(.prerelease == false) | .tag_name[1:]'
                            """,
                            returnStdout: true
                        ).trim()
                        println("Latest Tag: " + latestTag)
                    }
                }
            }
        }

        stage ("Clone Signal") {
            steps {
                dir("signal-desktop") {
                    checkout ([
                        $class: "GitSCM",
                        branches: [
                            [
                                name: "refs/tags/v" + latestTag,
                            ],
                        ],
                        userRemoteConfigs: [
                            [
                                url: "https://github.com/signalapp/Signal-Desktop.git",
                            ],
                        ],
                        extensions: [
                            [
                                $class: "CloneOption",
                                shallow: true,
                                depth: 1
                            ],
                            [
                                $class: "CheckoutOption",
                                timeout: 2
                            ],
                        ],
                    ])
                }
            }
        }

        stage ("Build Signal") {
            steps {
                container ("node") {
                    script {
                        writeFile(file: workspace + "/test-chamber-13.lan.root.crt", text: functions.getCurrentRootCA())
                        sh """
                            git config --global --add safe.directory '*'
                            apt-get update -yqq
                            apt-get install -yqq jq
                            mkdir -p /usr/local/share/.config/yarn/global/
                            touch /usr/local/share/.config/yarn/global/.yarnclean
                            cd ${workspace}/signal-desktop
                            cat package.json | jq '.scripts."build:electron" |= . + " --linux AppImage --publish=never"' > with_appimage_package.json
                            mv -f with_appimage_package.json package.json
                            yarn install --frozen-lockfile
                            yarn build
                        """

                        outputFile = sh (
                            script: """
                                basename \$(find ${workspace}/signal-desktop/ -name "*.AppImage")
                                """,
                            returnStdout: true
                        ).trim()
                    }
                }
            }
        }

        stage ('Push Artifacts') {
            steps {
                script {
                    functions.pushArtifact(
                        repoCreds: "nexus-generic-upload-bot",
                        fileName: outputFile,
                        filePath: "${workspace}/signal-desktop/release/",
                        fileURL: "https://nexus.c.test-chamber-13.lan/repository/generic/signal/"
                    )
                }
            }
        }
    }
}