// Don't forget to add http://jenkins.dandaedre.com/gitea-webhook/post as a gitea webhook if is not in your organisation

pipeline {
    agent { label 'rust_no_docker' }                // any COULD work, but prefer this label for mdbooks
    /* ===============
    BEGIN USER CONFIG
    ================== */
    environment {
        // The book name
        BOOK_NAME = "M6S_Guide"
        // Change with desired plugins
        MDB_PLUGIN_LIST = ""

        // Book is usually a good intermediate name
        MDBOOK_BUILD_DIR = "book"
        // Infered deploy directory
        DEPLOY_DIR = "/mnt/books/FFXIV_Guides/$BOOK_NAME"
    }

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

    stages {
        stage('Checkout') {
            steps {
                checkout scm                              // Checkout intead of full clone
            }
        }

        stage('Install mdBook') {
            steps {
                sh 'cargo install mdbook && echo "mdBook already installed"'    // Install the latest mdBooks
            }
        }

        // stage('Install plugins'){
        //     steps {
        //         sh 'cargo install ${MDB_PLUGIN_LIST}'
        //     }
        // }

        stage('Build Book') {
            steps {
                sh 'mdbook build'
            }
        }

        stage('Scan Warnings') {
            steps {
                recordIssues tools: [
                    groovyScript('mdbook_preprocessor_import')
                ],
                qualityGates: [
                    [threshold: 1, type: 'TOTAL', unstable: true],
                    [threshold: 1, type: 'TOTAL_ERROR', unstable: false] 
                ]
            }
        }

        stage('Deploy to Books') {
            steps {
                sh 'echo "Deploying to ${DEPLOY_DIR}"'
                sh 'mkdir -p ${DEPLOY_DIR}'
                // sh 'rm -rf ${DEPLOY_DIR}/*'                                  // This would be the nuclear approach
                // sh 'cp -r ${MDBOOK_BUILD_DIR}/* ${DEPLOY_DIR}/'              // Instead a rsync seems more sensible
                sh 'rsync -a --delete  ${MDBOOK_BUILD_DIR}/ ${DEPLOY_DIR}/'
            }
        }
    }

    post {
        success {
            echo '✅ mdBook Built!'
            // publishChecks name: 'example', title: 'Pipeline Check', summary: 'check through pipeline',
            //     text: 'you can publish checks in pipeline script',
            //     detailsURL: 'https://github.com/jenkinsci/checks-api-plugin#pipeline-usage',
            //     actions: [[label:'an-user-request-action', description:'actions allow users to request pre-defined behaviours', identifier:'an unique identifier']]

        }
        failure {
            echo '❌ mdbook Failed to Build'
        }
    }
}

