MACHINE_CLASSES = [
    "consul-master",
    "dns-auth",
    "dns-resolver",
    "squid-proxy",
    "pop-master"
]

def validMachineClass(String name) {
    if (params.machineClasses == "all") {
        return true
    }
    for (String machineClass: params.machineClasses.split(',')) {
        if (name == machineClass) {
            return true
        }
    }
    return false
}

def deployArtifact(String machineClass, boolean startedByCron) {
    if (!(startedByCron || validMachineClass(machineClass))) {
        return
    }
    withAWS(role: "jenkins-admin-access", roleAccount: "458835690105", region: "us-west-2") {
        switch (env.BRANCH_NAME) {
            case 'main':
                sh """
                    python ./scripts/upload_deployment_artifact.py $machineClass-deployment-artifacts puppet-deploy.zip
                """
                break
            default:
                echo "Not a main branch, artifact uploading is skipped."
        }
    }
}

startedByCron = (currentBuild.getRawBuild().getCause(hudson.triggers.TimerTrigger$TimerTriggerCause) != null)

uploads = [:]
MACHINE_CLASSES.each { machineClass ->
    uploads[machineClass] = { deployArtifact(machineClass, startedByCron) }
}

pipeline {
    agent any // the entire pipeline stages can be executed on any available jenkins agent
    triggers {
        // jenkins time is in UTC, 17 is 9am in PST and 10am in PDT
        cron(env.BRANCH_NAME == 'main' ? '33 17 * * 1-5' : '')
    }
    parameters {
         string(name: 'machineClasses', defaultValue: '', description: 'Comma separated list of the machine classes to run puppet on or "all" to run on all machine classes')
         string(name: 'puppetEnvironment', defaultValue: 'production', description: 'Puppet environment to use for the run')
         string(name: 'codedeployRegion', defaultValue: '', description: 'codedeploy region for your application')
    }
    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') { // build the artifact
            steps {
                build(
                    job: 'video-coreservices/puppet-environment-renderer/main',
                    parameters: [string(name: 'puppetEnvironment', value: params.puppetEnvironment)],
                    wait: true,
                )
                script {
                    sh """
                        export PUPPET_ENVIRONMENT=${params.puppetEnvironment} CODEDEPLOY_REGION=${params.codedeployRegion}
                        make clean
                        make output -e
                    """
                }
            }
        }
        stage("deploy") { // deploy the artifacts to the control account
            steps {
                script {
                    parallel(uploads)
                }
            }
        }
    }
}
