pipeline {
    agent any
    
    environment {
        VAULT_PASSWORD = credentials('vault_password')
    }

    parameters {
        choice(name: 'SITE_OPTION', choices: ['SiteA', 'SiteB', 'SiteA&B'], description: 'Select which site to deploy')
        string(name: 'ADDITIONAL_CONTENT', defaultValue: 'Новое сообщение', description: 'Additional content to be included in the site')
    }
 
    stages {
        stage('Decrypt SSH Key') {
            steps {
                script {
                    def tempDir = '/tmp/' + UUID.randomUUID().toString()
                    env.TEMP_DIR = tempDir
                    sh "mkdir -p ${tempDir}"

                    def decryptedKeyFile = "${tempDir}/id_ed25519"
                    def vaultPassFile = "${tempDir}/vault_pass"

                    writeFile file: vaultPassFile, text: VAULT_PASSWORD

                    sh """
                    ansible-vault decrypt ./ansible/id_ed25519_vault --output=${decryptedKeyFile} --vault-password-file=${vaultPassFile}
                    """

                    env.DECYPTED_KEY_FILE = decryptedKeyFile
                }
            }
        }

        stage('Deploy Site') {
            steps {
                script {
                    def sanitized_content = params.ADDITIONAL_CONTENT.replaceAll("'", "\\'").replaceAll('"', '\\"')
                    
                    def siteOption = params.SITE_OPTION
                    def hostsFile = env.HOSTS_FILE 

                    def targetGroups = ''
                    if (siteOption == 'SiteA') {
                        targetGroups = 'SiteA'
                    } else if (siteOption == 'SiteB') {
                        targetGroups = 'SiteB'
                    } else if (siteOption == 'SiteA&B') {
                        targetGroups = 'SiteA,SiteB,proxy'
                    }

                    ansiblePlaybook(
                        playbook: 'ansible/playbook.yml',
                        inventory: "ansible/inventory.yml",
                        extraVars: [
                            additional_content: sanitized_content,
                            ansible_ssh_private_key_file: env.DECYPTED_KEY_FILE
                        ],
                        limit: targetGroups
                    )
                }
            }
        }
    }
 
    post {
        always {
            script {
                if (env.TEMP_DIR) {
                    sh "rm -rf ${env.TEMP_DIR}"
                }
            }
        }
        success {
            echo 'Deployment completed successfully.'
        }
        failure {
            echo 'Deployment failed. Please check the logs for more details.'
        }
    }
}