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

def deployTo(String targetDir) {
    sh "echo \"Deploying to ${targetDir}\""
    sh "mkdir -p ${targetDir}"

    sh "qpdf --encrypt billy billy 40 -- --allow-weak-crypto \"${MSTR_BOOK}\" \"enc_${MSTR_BOOK}\""

    sh "rsync -a --delete \"enc_${MSTR_BOOK}\" \"${targetDir}/\""
    sh "rsync -a --delete \"${FULL_BOOK}\"   \"${targetDir}/\""
    sh "rsync -a --delete \"${PLYR_BOOK}\"   \"${targetDir}/\""
    sh "rsync -ar --delete --mkpath \"${HNDB_DIR}\"   \"${targetDir}/${HNDB_DIR}\""
}
pipeline {
    agent { label 'latex_no_docker' }
    /* ===============
    BEGIN USER CONFIG
    ================== */

    environment {
        FULL_BOOK = "Ravenous_build.pdf"
        PLYR_BOOK = "Player_handbook_build.pdf"
        MSTR_BOOK = "Master_handbook_build.pdf"
        HNDB_DIR  = "Handbooks/"
        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 {
                sh 'ls ravenous_databases'
                // sh 'ls'
                checkout scm                              // Checkout intead of full clone
                sh 'git submodule update --init --recursive'
            }
        }

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

        stage('Install plugins'){
            steps {
                sh 'pkg install -y qpdf'                 // 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 {
                    def reviewBranches   = ['origin/review', 'review']
                    def devciBranches    = ['origin/dev-ci',  'dev-ci' ]
                    def masterBranches   = ['origin/master',  'master' ]

                    if (reviewBranches.contains(env.BRANCH_NAME)) {
                        deployTo("${DEPLOY_DIR}_review")
                    } else if (devciBranches.contains(env.BRANCH_NAME)) {
                        deployTo("${DEPLOY_DIR}_dev")
                    } else if (masterBranches.contains(env.BRANCH_NAME)) {
                        deployTo(DEPLOY_DIR)
                    } else {
                        echo "Unknown branch: ${env.BRANCH_NAME} — skipping deploy steps."
                        return   // exit this script block early
                    }
                }
            }
        }
    }

    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}\""
    // Create the directories needed for fonts / radar images
    // sh 'mkdir -p ~/.local/share/fonts/'
    // sh 'mkdir -p ./Images/Radar/'
    // sh 'mkdir -p ./Bestiaire/'

    // sh 'ravenous-tools tablegen -e all'
    // sh 'ls ravenous_databases'
    // sh 'ravenous-tools monsters export --all'


    // // 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 generate'
    // /// Generate craft
    // sh 'ravenous-tools weapons all -e ./Craft/'

    // /* 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
    // }
    sh './build.sh --raw full'
    sh "./all_players.sh --raw"
    sh './build.sh --raw player'
}
