pipeline {
    agent any

    environment {
        PROD_HOST   = '106.54.23.149'
        PROD_USER   = 'ubuntu'
        DEPLOY_DIR  = '/var/www/docs.xuqinmin.com/site'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build Docs') {
            steps {
                bat '''
                    chcp 65001 > nul
                    pip3 install mkdocs-material --quiet
                    python -c "import sys; sys.stdout.reconfigure(encoding='utf-8'); import subprocess; subprocess.run([sys.executable, '-X', 'utf8', '-m', 'mkdocs', 'build', '--clean', '--site-dir', 'site'])"
                '''
            }
        }

        stage('Deploy') {
            steps {
                withCredentials([sshUserPrivateKey(credentialsId: 'PROD_SSH_KEY', keyFileVariable: 'SSH_KEY')]) {
                    bat '''
                        cd site
                        tar -czf ../site.tar.gz *
                        ssh -i %SSH_KEY% -o StrictHostKeyChecking=no -o ConnectTimeout=30 %PROD_USER%@%PROD_HOST% "mkdir -p %DEPLOY_DIR% && sudo rm -rf %DEPLOY_DIR%/* && sudo chown -R %PROD_USER%:%PROD_USER% %DEPLOY_DIR%"
                        scp -i %SSH_KEY% -o StrictHostKeyChecking=no -o ConnectTimeout=30 ../site.tar.gz %PROD_USER%@%PROD_HOST%:%DEPLOY_DIR%/
                        ssh -i %SSH_KEY% -o StrictHostKeyChecking=no -o ConnectTimeout=30 %PROD_USER%@%PROD_HOST% "cd %DEPLOY_DIR% && tar -xzf site.tar.gz && rm -f site.tar.gz"
                    '''
                }
            }
        }
    }

    post {
        success {
            echo 'Docs deployed: https://docs.xuqinmin.com/'
        }
        failure {
            echo 'Docs deployment failed!'
        }
    }
}
