// Don't forget to add http://192.168.1.37:8080/gitea-webhook/post as a gitea webhook

pipeline {
    agent { label 'latex_no_docker' }
    /* ===============
    BEGIN USER CONFIG
    ================== */

    environment {
        FULL_BOOK = "Ravenous_build.pdf"
        PLYR_BOOK = "Player_handbook_build.pdf"
        PLYR_BOOK = "Master_handbook_build.pdf"
        MDBOOK_BUILD_DIR = "book"                    // Don't change, it allows the build script & mdBook to know where the book is
        DEPLOY_DIR = "/mnt/books/Ravenous"           // Important, all books are in /mnt/book
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm                              // Checkout intead of full clone
                // sh 'git submodule update --init'
            }
        }

        stage('Install ravenous-tools') {
            steps {
                sh 'cargo install --git https://proxy.dandaedre.com/gitea/Ravenous/ravenous-tools.git || echo "ravenous-tolls already installed"'    // Install the latest mdBooks
            }
        }

        // stage('Install plugins'){
        //     steps {
        //         sh 'cargo install mdbook-admonish'                 // Change with desired plugins
        //     }
        // }

        /* ===============
         END USER CONFIG
        ================== */

        stage('Build Book') {
            steps {
                script {

                    // ----------------------------------------------------
                    // Branch lookup – feel free to add more names if needed.
                    // ----------------------------------------------------
                    def reviewBranches   = ['origin/review', 'review',
                                            'origin/dev-ci','dev-ci']
                    def masterBranches   = ['origin/master', 'master']

                    // Decide which deployment directory we should use
                    def targetDir
                    if (reviewBranches.contains(env.BRANCH_NAME)) {
                        targetDir = "${DEPLOY_DIR}_review"
                    } else if (masterBranches.contains(env.BRANCH_NAME)) {
                        targetDir = DEPLOY_DIR
                    } else {
                        echo "Unknown branch: ${env.BRANCH_NAME} — skipping build."
                        return   // exit the script block early
                    }

                    // ----------------------------------------------------
                    // Run all of the shared steps with the selected dir
                    // ----------------------------------------------------
                    runBuild(targetDir)
                }
            }
        }

        stage('Deploy to Books') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'origin/review' || env.BRANCH_NAME == 'review') {
                        sh 'echo "Deploying to ${DEPLOY_DIR}_review"'
                        sh 'mkdir -p ${DEPLOY_DIR}_review'
                        sh 'qpdf --encrypt billy billy 40 -- --allow-weak-crypto ${MSTR_BOOK}$ enc_${MSTR_BOOK}$'
                        sh 'rsync -a --delete "enc_${MSTR_BOOK}" "${DEPLOY_DIR}_review/"'
                        sh 'rsync -a --delete "${FULL_BOOK}" "${DEPLOY_DIR}_review/"'
                        sh 'rsync -a --delete "${PLYR_BOOK}" "${DEPLOY_DIR}_review/"'
                    } else if (env.BRANCH_NAME == 'origin/dev-ci' || env.BRANCH_NAME == 'dev-ci') {
                        sh 'echo "Deploying to ${DEPLOY_DIR}_dev"'
                        sh 'mkdir -p ${DEPLOY_DIR}_dev'
                        sh 'qpdf --encrypt billy billy 40 -- --allow-weak-crypto ${MSTR_BOOK}$ enc_${MSTR_BOOK}$'
                        sh 'rsync -a --delete "enc_${MSTR_BOOK}" "${DEPLOY_DIR}_dev/"'
                        sh 'rsync -a --delete "${FULL_BOOK}" "${DEPLOY_DIR}_dev/"'
                        sh 'rsync -a --delete "${PLYR_BOOK}" "${DEPLOY_DIR}_dev/"'
                    } else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') {
                        sh 'echo "Deploying to ${DEPLOY_DIR}"'
                        sh 'mkdir -p ${DEPLOY_DIR}'
                        sh 'rsync -a --delete "enc_${MSTR_BOOK}" "${DEPLOY_DIR}/"'
                        sh 'rsync -a --delete "${FULL_BOOK}" "${DEPLOY_DIR}/"'
                        sh 'rsync -a --delete "${FULL_BOOK}" "${DEPLOY_DIR}/"'
                        sh 'rsync -a --delete "${PLYR_BOOK}" "${DEPLOY_DIR}/"'
                    } else {
                        echo "Unknown branch: ${env.BRANCH_NAME} — skipping deploy steps."
                    }
                }
            }
        }
    }

    post {
        success {
            publishChecks conclusion: 'SUCCESS', name: 'Build Successful', summary: 'The build was successful', text: 'The build was sucessful', title: 'Build Successful'
            echo '✅Site Deployed!'
        }
        failure {
            publishChecks conclusion: 'FAILURE', name: 'Build Failed', summary: 'The build failed', text: 'The build was a failure', title: 'Build failed'
            echo '❌Site Failed to Deploy'
        }
        unstable{
            publishChecks conclusion: 'ACTION_REQUIRED', name: 'Build Unstable', summary: 'Unstable build', text: 'Unstable build', title: 'Build Unstable'
        }
    }
}

/**
 * All commands that were duplicated in the original script.
 *
 * @param deployDir The directory that will receive the output files.
 */
def runBuild(String deployDir) {
    sh "echo \"Deploying to ${deployDir}\""
    sh 'ravenous-tools tablegen -e all'

    // Create the directories needed for fonts / radar images
    sh 'mkdir -p ~/.local/share/fonts/'
    sh 'mkdir -p ./Images/Radar/'

    // Move the font into place (only needs doing once)
    sh 'mv ./Ressources/lmroman8-regular.ttf ~/.local/share/fonts/'

    // Load and generate graphs
    sh 'ravenous-tools graphs load'
    sh 'ravenous-tools graphs gen'

    /* Build each of the three TeX documents twice – once for a
       normal build, once to make sure the glossary / cross‑refs
       are correctly updated. */
    ['Player_handbook.tex',
     'Master_handbook.tex',
     'Ravenous.tex'].each { texFile ->
        sh "ravenous-tools make -N ${texFile}"
        sh "ravenous-tools make -t glossaries ${texFile}"
        sh "ravenous-tools make -N ${texFile}" // second build for correct references
    }
}
