@Library('flexo-libs')_

pipeline {
    agent any // the entire pipeline stages can be executed on any available jenkins agent
    parameters {
         string(name: 'puppetEnvironment', defaultValue: 'production', description: 'Puppet environment to use for the run')
    }
    options {
        timestamps() // prepend all lines of console log with a timestamp
        ansiColor('xterm') // ANSI escape sequences, including color, to Console Output
    }

    stages {
        stage('clean') { // discard artifacts from previous executions
            steps {
                cleanWs()
            }
        }

        stage('checkout') { // checkout the source code
            steps {
                checkout scm
            }
        }
        stage('build') {
            steps {
                script {
                    sshagent(credentials: ['git-aws-read-key']) {
                        sh """
                            PACKER_VERSION=1.7.4
                            PACKER=./packer
                            until [ -x \$PACKER ] && [ "\$(\$PACKER --version)" = "\$PACKER_VERSION" ]; do
                                wget -cqO /tmp/packer_\${PACKER_VERSION}_linux_amd64.zip "https://releases.hashicorp.com/packer/\${PACKER_VERSION}/packer_\${PACKER_VERSION}_linux_amd64.zip"
                                unzip /tmp/packer_\${PACKER_VERSION}_linux_amd64.zip
                            done

                            rm -f frozen_*.tgz
                            \$PACKER build -var puppetEnvironment=${params.puppetEnvironment} r10k.json
                        """
                    }
                }
            }
        }
        stage('upload') {
            steps {
                script {
                    roleName = "puppet-environment-renderer-upload-role-staging"
                    if (env.BRANCH_NAME == 'main') {
                        roleName = "puppet-environment-renderer-upload-role-prod"
                    }
                    withAgentAWS(role: roleName, roleAccount: "181769184623", region: "us-west-2") {
                        sh """
                            ./jenkins-upload.sh
                        """
                    }
                }
            }
        }
    }
}
