pipeline {
    agent any

    parameters {
        choice(
            name: 'PLAYBOOK',
            choices: ['update.yaml', 'snapshotAndUpdate.yaml', 'dockerUpdate.yml', 'dockerPrune.yaml', 'newMachine.yaml'],
            description: 'Select the playbook to run'
        )
        string(
            name: 'LIMIT',
            defaultValue: '',
            description: 'Limit to specific hosts or groups (e.g., "vms", "lxcs", "update_targets", or hostname) no.lan required'
        )
        booleanParam(
            name: 'DRY_RUN',
            defaultValue: false,
            description: 'Run in check mode (no changes made)'
        )
        booleanParam(
            name: 'CLEANUP_SNAPSHOTS',
            defaultValue: false,
            description: 'Remove snapshots after successful update (only for snapshotAndUpdate.yaml)'
        )
    }

    environment {
        PROXMOX_URL = 'https://192.168.0.166:8006'
        PROXMOX_USER = 'dynamic-inventory@pve'
        PROXMOX_TOKEN_ID = 'dynamic-inventory'
        PROXMOX_TOKEN_SECRET = credentials('PROXMOX_TOKEN_SECRET')
        ANSIBLE_HOST_KEY_CHECKING = 'False'
    }

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

        stage('Verify Inventory') {
            steps {
                sh '''
                    echo "Testing dynamic inventory connection..."
                    ansible-inventory -i inventories/inventory.proxmox.yml --list | head -10
                '''
            }
        }

        stage('Run Playbook') {
            steps {
                script {
                    // Set default limits based on playbook if not specified
                    def limitValue = params.LIMIT
                    if (!params.LIMIT) {
                        if (params.PLAYBOOK in ['dockerUpdate.yml', 'dockerPrune.yaml']) {
                            limitValue = 'docker_hosts'
                        }
                    }
                    def limitFlag = limitValue ? "--limit '${limitValue}'" : ''
                    def checkFlag = (params.DRY_RUN == true) ? '--check --diff' : ''
                    def extraVars = (params.CLEANUP_SNAPSHOTS == true) ? "-e cleanup_old_snapshots=true" : ''

                    echo "DRY_RUN parameter: ${params.DRY_RUN}"
                    echo "Check flag: '${checkFlag}'"
                    echo "Limit: '${limitValue}'"

                    sh """
                        ansible-playbook \
                            -i inventories/inventory.proxmox.yml \
                            playbooks/${params.PLAYBOOK} \
                            ${limitFlag} \
                            ${checkFlag} \
                            ${extraVars}
                    """
                }
            }
        }
    }

    post {
        success {
            echo "Playbook ${params.PLAYBOOK} completed successfully"
        }
        failure {
            echo "Playbook ${params.PLAYBOOK} failed"
        }
    }
}
