// Settings
@Library('jenkins-devops-cicd-library') _
import com.bnpparibas.release.*

// Run an arbitrary command on Linux FQDN target(s). No inventory.
// Shared creds + ansible run live in projects_deploy/_ansible.groovy.

pipeline {
    agent { label 'Bnpp-Ansible' }

    parameters {
        choice(name: 'Environment', choices: ['DEV', 'SIT', 'STG', 'PRD'],
               description: 'Selects the CyberArk safe / superuser.')
        string(name: 'TargetHosts', defaultValue: '',
               description: 'Target FQDN(s), comma-separated, e.g. eurvlii90521.xmp.net.intra')
        string(name: 'ShellCommand', defaultValue: '',
               description: 'Command to run (shell syntax).')
        choice(name: 'RunOnAllNodes', choices: ['no', 'yes'],
               description: 'no => run once on a single host / yes => run on every host.')
        choice(name: 'ElevatePrivileges', choices: ['no', 'yes'],
               description: 'yes => become the service account via CyberArk.')
    }

    stages {
        stage('Validate') {
            steps {
                script {
                    if (!params.TargetHosts?.trim()) { error('TargetHosts is required.') }
                    if (!params.ShellCommand?.trim()) { error('ShellCommand is required.') }
                }
            }
        }

        stage('Run command') {
            steps {
                script {
                    def ansible = load 'deployment/projects_deploy/_ansible.groovy'
                    ansible.run(
                        environment: params.Environment,
                        os:          'linux',
                        playbook:    'projects_deploy/run_command_linux.yml',
                        hosts:       params.TargetHosts,
                        extraVars: [
                            ShellCommand:      params.ShellCommand,
                            RunOnAllNodes:     params.RunOnAllNodes,
                            ElevatePrivileges: params.ElevatePrivileges
                        ]
                    )
                }
            }
        }
    }
}
