#!/usr/bin/env groovy

/*
 * Set up the Azure VM Cloud plugin.
 *
 * This file is generated from an ERB template!
 */

import jenkins.model.*
import com.microsoft.azure.vmagent.*
import com.microsoft.azure.util.*

import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.Domain

final String maxAgents                      = System.env.get('MAX_AGENTS') ?: '2'
final String cloudName                      = 'Azure'
final String githubUser                     = System.env.get('GITHUB_USER') ?: 'max-the-code-monkey'
final String resourceGroup                  = "azureagents-for-codevalet"
final String credentialsId                  = 'azure-agents-credential'
final String adminCredentialsId             = 'azure-agent-admin-credential'
final String tenantId                       = System.env.get('AZURE_TENANT_ID') ?: 'dummy-tenant-id'
final String subscriptionId                 = System.env.get('AZURE_SUBSCRIPTION_ID') ?: 'dummy-subscription-id'
final String clientId                       = System.env.get('AZURE_CLIENT_ID') ?: 'dummy-client-id'
final String clientSecret                   = System.env.get('AZURE_CLIENT_SECRET') ?: 'dummy-secret'
CredentialsScope scope                      = CredentialsScope.valueOf('SYSTEM')
AzureCredentials.ServicePrincipal principle = AzureCredentials.getServicePrincipal(credentialsId)
final String id                             = java.util.UUID.randomUUID().toString()
final Credentials c                         = new UsernamePasswordCredentialsImpl(scope,
                                                                                    adminCredentialsId,
                                                                                    adminCredentialsId,
                                                                                    'azureuser',
                                                                                    id)

SystemCredentialsProvider.instance.store.addCredentials(Domain.global(), c)

println ">> Credential: ${id}"

/* If the credentials hasn't already been defined, let's create one! */
if (principle.isBlank()) {
    AzureCredentials credential = new AzureCredentials(scope,         /* Scope for the credential */
                                      credentialsId, /* */
                                      'Azure credentials for provisioning agent', /* description */
                                      subscriptionId,           /* subscriptionId */
                                      clientId,                /* clientId */
                                      clientSecret)           /* clientSecret */
    credential.tenant = tenantId

    SystemCredentialsProvider.instance.store.addCredentials(Domain.global(), credential)
}


Jenkins.instance.clouds.clear()
def cloud = Jenkins.instance.clouds.find { it.name == cloudName }

/* Avoid adding the AzureVMCloud over and over and over again */
if (cloud == null) {
    cloud = new AzureVMCloud(cloudName,         /* Cloud Name */
                                credentialsId,      /* credentials id */
                                maxAgents,          /* Max Agents */
                                '1200',             /* Deployment Timeout (s) */
                                'existing',              /* Resource group reference type */
                                '',      /* New resource group name */
                                resourceGroup,                 /* Existing resource group name */
                                null)        /* VM Templates */
    Jenkins.instance.clouds.add(cloud)
}


/* Nuke all our templates */
cloud.clearVmTemplates()

final String agentWorkspace = '/home/azureuser/workspace'
def retentionTime = null
def imageReference = null
def vmTemplate = null
def vhd = null

<% agents.each_pair do |name, d| %>

    vhd = '<%= d['image']['vhd'] %>'
    retentionTime = new AzureVMCloudRetensionStrategy(<%= d['retention'] %>)
    imageReference = new AzureVMAgentTemplate.ImageReferenceTypeClass(vhd, vhd, vhd, vhd, vhd)
    vmTemplate = new AzureVMAgentTemplate('<%= name %>',
                                '<%= d['description'] %>', /* description */
                                '<%= d['labels'].join(' ') %>', /* labels */
                                 'West US', /* location */
                                 '<%= d['size'] %>', /* VM Size */
                                 'existing', /* Storage account Name reference type */
                                 'Standard_LRS', /* Storage account type */
                                 '', /* new storage account name */
                                 'codevaletimages', /* existing storage account name */
                                 'unmanaged', /* disk type */
                                 '<%= d['executors'] %>', /* number of executors */
                                 'NORMAL', /* Usage mode */
                                 '', /* built-in image */
                                 false, /* install git */
                                 false, /* install maven */
                                 false, /* install docker */
                                 'Linux', /* OS type */
                                 'custom', /* image top level type */
                                 false, /* image reference? */
                                 imageReference, /* image reference class */
                                 'SSH', /* agent launch method */
                                 false, /* pre install SSH */
                                 '<%= d['initscript']%>', /* init script */
                                 adminCredentialsId, /* admin credential Id */
                                 '', /* virtual network name */
                                 '', /* virtual network resource group name */
                                 '', /* subnet name */
                                 false, /* use private IP */
                                 '', /* Network security group name */
                                 agentWorkspace, /* agent workspace */
                                 '', /* JVM options */
                                 retentionTime, /* retention time */
                                 false, /* shutdown on idle */
                                 false, /* template disabled */
                                 '', /* template status details */
                                 true, /* execute init script as root */
                                 true /* do not use machine if init fails */
        )
    vmTemplate.azureCloud = cloud
    cloud.addVmTemplate(vmTemplate)

<% end %>
