{{- if not .Values.master.customConfigMap }}
{{- $jenkinsHome := .Values.master.jenkinsHome -}}

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" . }}
  namespace: {{ template "jenkins.namespace" . }}
  labels:
    "app.kubernetes.io/name": '{{ template "jenkins.name" .}}'
    "helm.sh/chart": "{{ .Chart.Name }}-{{ .Chart.Version }}"
    "app.kubernetes.io/managed-by": "{{ .Release.Service }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
    "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
data:
{{- if .Values.master.enableXmlConfig }}
  config.xml: |-
    <?xml version='1.0' encoding='UTF-8'?>
    <hudson>
      <disabledAdministrativeMonitors/>
{{- if .Values.master.imageTag }}
      <version>{{ .Values.master.imageTag }}</version>
{{- else }}
      <version>{{ .Values.master.tag }}</version>
{{- end }}
      <numExecutors>{{ .Values.master.numExecutors }}</numExecutors>
      <mode>{{ .Values.master.executorMode }}</mode>
      <useSecurity>{{ .Values.master.useSecurity }}</useSecurity>
{{ .Values.master.authorizationStrategy | indent 6 }}
{{ .Values.master.securityRealm | indent 6 }}
      <disableRememberMe>{{ .Values.master.disableRememberMe }}</disableRememberMe>
      <projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
      <workspaceDir>${JENKINS_HOME}/workspace/${ITEM_FULLNAME}</workspaceDir>
      <buildsDir>${ITEM_ROOTDIR}/builds</buildsDir>
{{- if .Values.master.enableRawHtmlMarkupFormatter }}
      <markupFormatter class="hudson.markup.RawHtmlMarkupFormatter" plugin="antisamy-markup-formatter">
        <disableSyntaxHighlighting>true</disableSyntaxHighlighting>
      </markupFormatter>
{{- else }}
      <markupFormatter class="hudson.markup.EscapedMarkupFormatter"/>
{{- end }}
      <jdks/>
      <viewsTabBar class="hudson.views.DefaultViewsTabBar"/>
      <myViewsTabBar class="hudson.views.DefaultMyViewsTabBar"/>
      <clouds>
        <org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud plugin="kubernetes@{{ template "jenkins.kubernetes-version" . }}">
          <name>kubernetes</name>
          <defaultsProviderTemplate>{{ .Values.master.slaveDefaultsProviderTemplate }}</defaultsProviderTemplate>
          <templates>
{{- if .Values.agent.enabled }}
  {{- include "jenkins.xml.podTemplate" . | nindent 12 }}
  {{- if .Values.additionalAgents }}
    {{- /* save .Values.agent */}}
    {{- $agent := .Values.agent }}
    {{- range $name, $additionalAgent := .Values.additionalAgents }}
      {{- /* merge original .Values.agent into additional agent to ensure it at least has the default values */}}
      {{- $additionalAgent := merge $additionalAgent $agent }}
      {{- /* set .Values.agent to $additionalAgent */}}
      {{- $_ := set $.Values "agent" $additionalAgent }}
      {{- include "jenkins.xml.podTemplate" $ | nindent 12 }}
    {{- end }}
    {{- /* restore .Values.agent */}}
    {{- $_ := set .Values "agent" $agent }}
  {{- end }}
{{- end }}
          </templates>
          <serverUrl>https://kubernetes.default</serverUrl>
          <skipTlsVerify>false</skipTlsVerify>
          <namespace>{{ template "jenkins.master.slaveKubernetesNamespace" . }}</namespace>
{{- if .Values.master.slaveJenkinsUrl }}
          <jenkinsUrl>{{ tpl .Values.master.slaveJenkinsUrl . }}</jenkinsUrl>
{{- else if .Values.master.slaveKubernetesNamespace }}
          <jenkinsUrl>http://{{ template "jenkins.fullname" . }}.{{ template "jenkins.namespace" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}</jenkinsUrl>
{{- else }}
          <jenkinsUrl>http://{{ template "jenkins.fullname" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}</jenkinsUrl>
{{- end }}

{{- if .Values.master.slaveJenkinsTunnel }}
          <jenkinsTunnel>{{ tpl .Values.master.slaveJenkinsTunnel . }}</jenkinsTunnel>
{{- else if .Values.master.slaveKubernetesNamespace }}
          <jenkinsTunnel>{{ template "jenkins.fullname" . }}-agent.{{ template "jenkins.namespace" . }}:{{ .Values.master.slaveListenerPort }}</jenkinsTunnel>
{{- else }}
          <jenkinsTunnel>{{ template "jenkins.fullname" . }}-agent:{{ .Values.master.slaveListenerPort }}</jenkinsTunnel>
{{- end }}
          <containerCap>{{ .Values.agent.containerCap }}</containerCap>
          <retentionTimeout>5</retentionTimeout>
          <connectTimeout>{{ .Values.master.slaveConnectTimeout }}</connectTimeout>
          <readTimeout>{{ .Values.master.slaveReadTimeout }}</readTimeout>
          <podLabels>
            <org.csanchez.jenkins.plugins.kubernetes.PodLabel>
              <key>jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}</key>
              <value>true</value>
            </org.csanchez.jenkins.plugins.kubernetes.PodLabel>
          </podLabels>
          <podRetention class="org.csanchez.jenkins.plugins.kubernetes.pod.retention.{{ .Values.agent.podRetention }}"/>
        </org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud>
      </clouds>
      <quietPeriod>5</quietPeriod>
      <scmCheckoutRetryCount>0</scmCheckoutRetryCount>
      <views>
        <hudson.model.AllView>
          <owner class="hudson" reference="../../.."/>
          <name>All</name>
          <filterExecutors>false</filterExecutors>
          <filterQueue>false</filterQueue>
          <properties class="hudson.model.View$PropertyList"/>
        </hudson.model.AllView>
      </views>
      <primaryView>All</primaryView>
      <slaveAgentPort>{{ .Values.master.slaveListenerPort }}</slaveAgentPort>
      <disabledAgentProtocols>
{{- range .Values.master.disabledAgentProtocols }}
        <string>{{ . }}</string>
{{- end }}
      </disabledAgentProtocols>
      <label>{{ .Values.master.customJenkinsLabels | join " " }}</label>
{{- if .Values.master.csrf.defaultCrumbIssuer.enabled }}
      <crumbIssuer class="hudson.security.csrf.DefaultCrumbIssuer">
{{- if .Values.master.csrf.defaultCrumbIssuer.proxyCompatability }}
        <excludeClientIPFromCrumb>true</excludeClientIPFromCrumb>
{{- end }}
      </crumbIssuer>
{{- end }}
      <nodeProperties/>
      <globalNodeProperties/>
      <noUsageStatistics>true</noUsageStatistics>
    </hudson>
{{- if .Values.master.scriptApproval }}
  scriptapproval.xml: |-
    <?xml version='1.0' encoding='UTF-8'?>
    <scriptApproval plugin="script-security@1.27">
      <approvedScriptHashes/>
      <approvedSignatures>
{{- range $key, $val := .Values.master.scriptApproval }}
        <string>{{ $val }}</string>
{{- end }}
      </approvedSignatures>
      <aclApprovedSignatures/>
      <approvedClasspathEntries/>
      <pendingScripts/>
      <pendingSignatures/>
      <pendingClasspathEntries/>
    </scriptApproval>
{{- end }}
  jenkins.model.JenkinsLocationConfiguration.xml: |-
    <?xml version='1.1' encoding='UTF-8'?>
    <jenkins.model.JenkinsLocationConfiguration>
      <adminAddress>{{ default "" .Values.master.jenkinsAdminEmail }}</adminAddress>
      <jenkinsUrl>{{ template "jenkins.url" . }}</jenkinsUrl>
    </jenkins.model.JenkinsLocationConfiguration>
  jenkins.CLI.xml: |-
    <?xml version='1.1' encoding='UTF-8'?>
    <jenkins.CLI>
{{- if .Values.master.cli }}
      <enabled>true</enabled>
{{- else }}
      <enabled>false</enabled>
{{- end }}
    </jenkins.CLI>
{{- end }}
  apply_config.sh: |-
{{- if .Values.master.initializeOnce }}
    if [ -f {{ .Values.master.jenkinsHome }}/initialization-completed ]; then
      echo "master was previously initialized, refusing to re-initialize"
      exit 0
    fi
{{- end }}
    echo "applying Jenkins configuration"
    mkdir -p {{ .Values.master.jenkinsRef }}/secrets/;
{{- if .Values.master.enableXmlConfig }}
    echo "apply XML configuration"
    echo "false" > {{ .Values.master.jenkinsRef }}/secrets/slave-to-master-security-kill-switch;
{{- if .Values.master.overwriteConfig }}
    echo "overwriting existing configuration"
    cp /var/jenkins_config/config.xml {{ .Values.master.jenkinsHome }};
    cp /var/jenkins_config/jenkins.CLI.xml {{ .Values.master.jenkinsHome }};
    cp /var/jenkins_config/jenkins.model.JenkinsLocationConfiguration.xml {{ .Values.master.jenkinsHome }};
  {{- if .Values.master.additionalConfig }}
  {{- range $key, $val := .Values.master.additionalConfig }}
    echo "copying additional configuration"
    cp /var/jenkins_config/{{- $key }} {{ $jenkinsHome }};
  {{- end }}
  {{- end }}
{{- else }}
    echo "copy XML configuration"
    yes n | cp -i /var/jenkins_config/config.xml {{ .Values.master.jenkinsHome }};
    yes n | cp -i /var/jenkins_config/jenkins.CLI.xml {{ .Values.master.jenkinsHome }};
    yes n | cp -i /var/jenkins_config/jenkins.model.JenkinsLocationConfiguration.xml {{ .Values.master.jenkinsHome }};
  {{- if .Values.master.additionalConfig }}
  {{- range $key, $val := .Values.master.additionalConfig }}
    yes n | cp -i /var/jenkins_config/{{- $key }} {{ $jenkinsHome }};
  {{- end }}
  {{- end }}
{{- end }}
{{- else }}
{{- if .Values.master.JCasC.enabled }}
    echo "disable Setup Wizard"
    # Prevent Setup Wizard when JCasC is enabled
    echo $JENKINS_VERSION > {{ .Values.master.jenkinsHome }}/jenkins.install.UpgradeWizard.state
    echo $JENKINS_VERSION > {{ .Values.master.jenkinsHome }}/jenkins.install.InstallUtil.lastExecVersion
{{- end }}
{{- end }}
{{- if .Values.master.overwritePlugins }}
    echo "remove all plugins from shared volume"
    # remove all plugins from shared volume
    rm -rf {{ .Values.master.jenkinsHome }}/plugins/*
{{- end }}
{{- if .Values.master.installPlugins }}
    echo "download plugins"
    # Install missing plugins
    cp /var/jenkins_config/plugins.txt {{ .Values.master.jenkinsHome }};
    rm -rf {{ .Values.master.jenkinsRef }}/plugins/*.lock
    /usr/local/bin/install-plugins.sh `echo $(cat {{ .Values.master.jenkinsHome }}/plugins.txt)`;
    echo "copy plugins to shared volume"
    # Copy plugins to shared volume
    yes n | cp -i {{ .Values.master.jenkinsRef }}/plugins/* /var/jenkins_plugins/;
{{- end }}
{{- if .Values.master.scriptApproval }}
    echo "configure script approval"
  {{- if .Values.master.overwriteConfig }}
    cp /var/jenkins_config/scriptapproval.xml {{ .Values.master.jenkinsHome }}/scriptApproval.xml;
  {{- else }}
    yes n | cp -i /var/jenkins_config/scriptapproval.xml {{ .Values.master.jenkinsHome }}/scriptApproval.xml;
  {{- end }}
{{- end }}
{{- if .Values.master.initScripts }}
    echo "copy init scripts"
    mkdir -p {{ .Values.master.jenkinsHome }}/init.groovy.d/;
    {{- if .Values.master.overwriteConfig }}
    rm -f {{ .Values.master.jenkinsHome }}/init.groovy.d/*.groovy
    {{- end }}
    yes n | cp -i /var/jenkins_config/*.groovy {{ .Values.master.jenkinsHome }}/init.groovy.d/;
{{- end }}
{{- if .Values.master.JCasC.enabled}}
  {{- if not .Values.master.sidecars.configAutoReload.enabled }}
    echo "copy configuration as code files"
    mkdir -p {{ .Values.master.jenkinsHome }}/casc_configs;
    rm -rf {{ .Values.master.jenkinsHome }}/casc_configs/*
    {{- if .Values.master.JCasC.configScripts }}
    cp -v /var/jenkins_config/*.yaml {{ .Values.master.jenkinsHome }}/casc_configs
    {{- end }}
  {{- end }}
{{- end }}
{{- if .Values.master.enableXmlConfig }}
{{- if .Values.master.credentialsXmlSecret }}
    echo "copy credentials.xml"
    yes n | cp -i /var/jenkins_credentials/credentials.xml {{ .Values.master.jenkinsHome }};
{{- end }}
{{- if .Values.master.jobs }}
    echo "copy jobs"
    for job in $(ls /var/jenkins_jobs); do
      mkdir -p {{ .Values.master.jenkinsHome }}/jobs/$job
      yes {{ if not .Values.master.overwriteJobs }}n{{ end }} | cp -i /var/jenkins_jobs/$job {{ .Values.master.jenkinsHome }}/jobs/$job/config.xml
    done
{{- end }}
{{- end }}
{{- if .Values.master.secretsFilesSecret }}
    echo "copy secrets"
    yes n | cp -i /var/jenkins_secrets/* {{ .Values.master.jenkinsRef }}/secrets/;
{{- end }}
    echo "finished initialization"
{{- if .Values.master.initializeOnce }}
    touch {{ .Values.master.jenkinsHome }}/initialization-completed
{{- end }}
{{- range $key, $val := .Values.master.initScripts }}
  init{{ $key }}.groovy: |-
{{ $val | indent 4 }}
{{- end }}
{{- if .Values.master.JCasC.enabled }}
  {{- if not .Values.master.sidecars.configAutoReload.enabled }}
# Only add config to this script if we aren't auto-reloading otherwise the pod will restart upon each config change:
{{- if .Values.master.JCasC.defaultConfig }}
  jcasc-default-config.yaml: |-
    {{- include "jenkins.casc.defaults" . |nindent 4}}
{{- end }}
{{- range $key, $val := .Values.master.JCasC.configScripts }}
  {{ $key }}.yaml: |-
{{ tpl $val $| indent 4 }}
{{- end }}
{{- end }}
{{- end }}
  plugins.txt: |-
{{- if .Values.master.installPlugins }}
  {{- range $installPlugin := .Values.master.installPlugins }}
    {{- $installPlugin | nindent 4 }}
  {{- end }}
  {{- range $addlPlugin := .Values.master.additionalPlugins }}
    {{- /* duplicate plugin check */}}
    {{- range $installPlugin := $.Values.master.installPlugins }}
      {{- if eq (splitList ":" $addlPlugin | first) (splitList ":" $installPlugin | first) }}
        {{- $message := print "[PLUGIN CONFLICT] master.additionalPlugins contains '" $addlPlugin "'" }}
        {{- $message := print $message " but master.installPlugins already contains '" $installPlugin "'." }}
        {{- $message := print $message " Override master.installPlugins to use '" $addlPlugin "' plugin." }}
        {{- fail $message }}
      {{- end }}
    {{- end }}
    {{- $addlPlugin | nindent 4 }}
  {{- end }}
{{- end }}
{{ else }}
{{ include "override_config_map" . }}
{{- end -}}
{{- if .Values.master.additionalConfig }}
{{- toYaml .Values.master.additionalConfig | indent 2 }}
{{- end }}
