{{- if not .Values.Master.CustomConfigMap }}

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" . }}
data:
  config.xml: |-
    <?xml version='1.0' encoding='UTF-8'?>
    <hudson>
      <disabledAdministrativeMonitors/>
      <version>{{ .Values.Master.ImageTag }}</version>
      <numExecutors>{{ .Values.Master.NumExecutors }}</numExecutors>
      <mode>NORMAL</mode>
      <useSecurity>{{ .Values.Master.UseSecurity }}</useSecurity>
{{- if not (empty .Values.Master.AuthorizationStrategy ) }}
{{ .Values.Master.AuthorizationStrategy | indent 6 }}
{{- else }}
      <authorizationStrategy class="hudson.security.FullControlOnceLoggedInAuthorizationStrategy">
        <denyAnonymousReadAccess>true</denyAnonymousReadAccess>
      </authorizationStrategy>
{{- end }}
{{- if .Values.Master.SecurityRealm }}
{{ .Values.Master.SecurityRealm | indent 6 }}
{{- else }}
      <securityRealm class="hudson.security.LegacySecurityRealm"/>
{{- end }}
      <disableRememberMe>false</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>
          <templates>
{{- if .Values.Agent.Enabled }}
            <org.csanchez.jenkins.plugins.kubernetes.PodTemplate>
              <inheritFrom></inheritFrom>
              <name>{{ .Values.Agent.PodName }}</name>
              <instanceCap>2147483647</instanceCap>
              <idleMinutes>0</idleMinutes>
              <label>{{ .Release.Name }}-{{ .Values.Agent.Component }} {{ .Values.Agent.CustomJenkinsLabels  | join " " }}</label>
              <nodeSelector>
                {{- $local := dict "first" true }}
                {{- range $key, $value := .Values.Agent.NodeSelector }}
                  {{- if not $local.first }},{{- end }}
                  {{- $key }}={{ $value }}
                  {{- $_ := set $local "first" false }}
                {{- end }}</nodeSelector>
                <nodeUsageMode>NORMAL</nodeUsageMode>
              <volumes>
{{- range $index, $volume := .Values.Agent.volumes }}
                <org.csanchez.jenkins.plugins.kubernetes.volumes.{{ $volume.type }}Volume>
{{- range $key, $value := $volume }}{{- if not (eq $key "type") }}
                  <{{ $key }}>{{ $value }}</{{ $key }}>
{{- end }}{{- end }}
                </org.csanchez.jenkins.plugins.kubernetes.volumes.{{ $volume.type }}Volume>
{{- end }}
              </volumes>
              <containers>
                <org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate>
                  <name>{{ .Values.Agent.SideContainerName }}</name>
                  <image>{{ .Values.Agent.Image }}:{{ .Values.Agent.ImageTag }}</image>
{{- if .Values.Agent.Privileged }}
                  <privileged>true</privileged>
{{- else }}
                  <privileged>false</privileged>
{{- end }}
                  <alwaysPullImage>{{ .Values.Agent.AlwaysPullImage }}</alwaysPullImage>
                  <workingDir>/home/jenkins</workingDir>
                  <command>{{ .Values.Agent.Command }}</command>
{{- if .Values.Agent.Args }}
                  <args>{{ .Values.Agent.Args }}</args>
{{- else }}
                  <args>${computer.jnlpmac} ${computer.name}</args>
{{- end }}
                  <ttyEnabled>{{ .Values.Agent.TTYEnabled }}</ttyEnabled>
                  # Resources configuration is a little hacky. This was to prevent breaking
                  # changes, and should be cleanned up in the future once everybody had
                  # enough time to migrate.
                  <resourceRequestCpu>{{.Values.Agent.Cpu | default .Values.Agent.resources.requests.cpu}}</resourceRequestCpu>
                  <resourceRequestMemory>{{.Values.Agent.Memory | default .Values.Agent.resources.requests.memory}}</resourceRequestMemory>
                  <resourceLimitCpu>{{.Values.Agent.Cpu | default .Values.Agent.resources.limits.cpu}}</resourceLimitCpu>
                  <resourceLimitMemory>{{.Values.Agent.Memory | default .Values.Agent.resources.limits.memory}}</resourceLimitMemory>
                  <envVars>
                    <org.csanchez.jenkins.plugins.kubernetes.ContainerEnvVar>
                      <key>JENKINS_URL</key>
{{- if .Values.Master.SlaveKubernetesNamespace }}
                      <value>http://{{ template "jenkins.fullname" . }}.{{.Release.Namespace}}:{{.Values.Master.ServicePort}}{{ default "" .Values.Master.JenkinsUriPrefix }}</value>
{{- else }}
                      <value>http://{{ template "jenkins.fullname" . }}:{{.Values.Master.ServicePort}}{{ default "" .Values.Master.JenkinsUriPrefix }}</value>
{{- end }}
                    </org.csanchez.jenkins.plugins.kubernetes.ContainerEnvVar>
                  </envVars>
                </org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate>
              </containers>
              <envVars>
{{- range $index, $var := .Values.Agent.envVars }}
                <org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
                  <key>{{ $var.name }}</key>
                  <value>{{ $var.value }}</value>
                </org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
{{- end }}
              </envVars>
              <annotations/>
{{- if .Values.Agent.ImagePullSecret }}
              <imagePullSecrets>
                <org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret>
                  <name>{{ .Values.Agent.ImagePullSecret }}</name>
                </org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret>
              </imagePullSecrets>
{{- else }}
              <imagePullSecrets/>
{{- end }}
              <nodeProperties/>
              <podRetention class="org.csanchez.jenkins.plugins.kubernetes.pod.retention.Default"/>
            </org.csanchez.jenkins.plugins.kubernetes.PodTemplate>
{{- end -}}
          </templates>
          <serverUrl>https://kubernetes.default</serverUrl>
          <skipTlsVerify>false</skipTlsVerify>
          <namespace>{{ default .Release.Namespace .Values.Master.SlaveKubernetesNamespace }}</namespace>
{{- if .Values.Master.SlaveKubernetesNamespace }}
          <jenkinsUrl>http://{{ template "jenkins.fullname" . }}.{{.Release.Namespace}}:{{.Values.Master.ServicePort}}{{ default "" .Values.Master.JenkinsUriPrefix }}</jenkinsUrl>
          <jenkinsTunnel>{{ template "jenkins.fullname" . }}-agent.{{.Release.Namespace}}:{{ .Values.Master.SlaveListenerPort }}</jenkinsTunnel>
{{- else }}
          <jenkinsUrl>http://{{ template "jenkins.fullname" . }}:{{.Values.Master.ServicePort}}{{ default "" .Values.Master.JenkinsUriPrefix }}</jenkinsUrl>
          <jenkinsTunnel>{{ template "jenkins.fullname" . }}-agent:{{ .Values.Master.SlaveListenerPort }}</jenkinsTunnel>
{{- end }}
          <containerCap>{{ .Values.Agent.ContainerCap }}</containerCap>
          <retentionTimeout>5</retentionTimeout>
          <connectTimeout>0</connectTimeout>
          <readTimeout>0</readTimeout>
          <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></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>
{{- if .Values.Master.JenkinsUrl }}
      <jenkinsUrl>{{ .Values.Master.JenkinsUrl }}</jenkinsUrl>
{{- else }}
  {{- if .Values.Master.HostName }}
    {{- if .Values.Master.Ingress.TLS }}
      <jenkinsUrl>https://{{ .Values.Master.HostName }}{{ default "" .Values.Master.JenkinsUriPrefix }}</jenkinsUrl>
    {{- else }}
      <jenkinsUrl>http://{{ .Values.Master.HostName }}{{ default "" .Values.Master.JenkinsUriPrefix }}</jenkinsUrl>
    {{- end }}
  {{- else }}
      <jenkinsUrl>http://{{ template "jenkins.fullname" . }}:{{.Values.Master.ServicePort}}{{ default "" .Values.Master.JenkinsUriPrefix }}</jenkinsUrl>
  {{- end}}
{{- end}}
    </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>
  apply_config.sh: |-
    mkdir -p /usr/share/jenkins/ref/secrets/;
    echo "false" > /usr/share/jenkins/ref/secrets/slave-to-master-security-kill-switch;
{{- if .Values.Master.OverwriteConfig }}
    cp /var/jenkins_config/config.xml /var/jenkins_home;
    cp /var/jenkins_config/jenkins.CLI.xml /var/jenkins_home;
    cp /var/jenkins_config/jenkins.model.JenkinsLocationConfiguration.xml /var/jenkins_home;
  {{- else }}
    yes n | cp -i /var/jenkins_config/config.xml /var/jenkins_home;
    yes n | cp -i /var/jenkins_config/jenkins.CLI.xml /var/jenkins_home;
    yes n | cp -i /var/jenkins_config/jenkins.model.JenkinsLocationConfiguration.xml /var/jenkins_home;
  {{- if .Values.Master.AdditionalConfig }}
{{- range $key, $val := .Values.Master.AdditionalConfig }}
    cp /var/jenkins_config/{{- $key }} /var/jenkins_home;
  {{- end }}
  {{- end }}
{{- end }}
{{- if .Values.Master.OverwritePlugins }}
    # remove all plugins from shared volume
    rm -rf /var/jenkins_home/plugins/*
{{- end }}
{{- if .Values.Master.InstallPlugins }}
    # Install missing plugins
    cp /var/jenkins_config/plugins.txt /var/jenkins_home;
    rm -rf /usr/share/jenkins/ref/plugins/*.lock
    /usr/local/bin/install-plugins.sh `echo $(cat /var/jenkins_home/plugins.txt)`;
    # Copy plugins to shared volume
    yes n | cp -i /usr/share/jenkins/ref/plugins/* /var/jenkins_plugins/;
{{- end }}
{{- if .Values.Master.ScriptApproval }}
    yes n | cp -i /var/jenkins_config/scriptapproval.xml /var/jenkins_home/scriptApproval.xml;
{{- end }}
{{- if and (.Values.Master.JCasC.enabled) (.Values.Master.Sidecars.configAutoReload.enabled) }}
  {{- if not .Values.Master.InitScripts }}
    mkdir -p /var/jenkins_home/init.groovy.d/;
    yes n | cp -i /var/jenkins_config/*.groovy /var/jenkins_home/init.groovy.d/;
  {{- end }}
{{- end }}
{{- if .Values.Master.InitScripts }}
    mkdir -p /var/jenkins_home/init.groovy.d/;
    yes n | cp -i /var/jenkins_config/*.groovy /var/jenkins_home/init.groovy.d/;
{{- end }}
{{- if .Values.Master.JCasC.enabled }}
  {{- if .Values.Master.Sidecars.configAutoReload.enabled }}
    bash -c 'ssh-keygen -y -f <(echo "${ADMIN_PRIVATE_KEY}") > /var/jenkins_home/key.pub'
  {{- else }}
    mkdir -p /var/jenkins_home/casc_configs;
    rm -rf /var/jenkins_home/casc_configs/*
    cp -v /var/jenkins_config/*.yaml /var/jenkins_home/casc_configs
  {{- end }}
{{- end }}
{{- if .Values.Master.CredentialsXmlSecret }}
    yes n | cp -i /var/jenkins_credentials/credentials.xml /var/jenkins_home;
{{- end }}
{{- if .Values.Master.SecretsFilesSecret }}
    yes n | cp -i /var/jenkins_secrets/* /usr/share/jenkins/ref/secrets/;
{{- end }}
{{- if .Values.Master.Jobs }}
    for job in $(ls /var/jenkins_jobs); do
      mkdir -p /var/jenkins_home/jobs/$job
      yes n | cp -i /var/jenkins_jobs/$job /var/jenkins_home/jobs/$job/config.xml
    done
{{- end }}
{{- range $key, $val := .Values.Master.InitScripts }}
  init{{ $key }}.groovy: |-
{{ $val | indent 4 }}
{{- end }}
{{- if .Values.Master.JCasC.enabled }}
  {{- if .Values.Master.Sidecars.configAutoReload.enabled }}
  init-add-ssh-key-to-admin.groovy: |-
    import jenkins.security.*
    import hudson.model.User
    import jenkins.security.ApiTokenProperty
    import jenkins.model.Jenkins
    User u = User.get("{{ .Values.Master.AdminUser | default "admin" }}")
    ApiTokenProperty t = u.getProperty(ApiTokenProperty.class)
    String sshKeyString = new File('/var/jenkins_home/key.pub').text
    keys_param = new org.jenkinsci.main.modules.cli.auth.ssh.UserPropertyImpl(sshKeyString)
    u.addProperty(keys_param)
    def inst = Jenkins.getInstance()
    def sshDesc = inst.getDescriptor("org.jenkinsci.main.modules.sshd.SSHD")
    sshDesc.setPort({{ .Values.Master.Sidecars.configAutoReload.sshTcpPort | default 1044 }})
    sshDesc.getActualPort()
    sshDesc.save()
  {{- else }}
# Only add config to this script if we aren't auto-reloading otherwise the pod will restart upon each config change:
{{- range $key, $val := .Values.Master.JCasC.ConfigScripts }}
  {{ $key }}.yaml: |-
{{ tpl $val $| indent 4 }}
{{- end }}
{{- end }}
{{- end }}
  plugins.txt: |-
{{- if .Values.Master.InstallPlugins }}
{{- range $index, $val := .Values.Master.InstallPlugins }}
{{ $val | indent 4 }}
{{- end }}
{{- if .Values.Master.JCasC.enabled }}
  {{- if not (contains "configuration-as-code" (quote .Values.Master.InstallPlugins)) }}
    configuration-as-code:{{ .Values.Master.JCasC.PluginVersion }}
  {{- end }}
  {{- if not (contains "configuration-as-code-support" (quote .Values.Master.InstallPlugins)) }}
    configuration-as-code-support:{{ .Values.Master.JCasC.SupportPluginVersion }}
  {{- end }}
{{- end }}
{{- end }}
{{ else }}
{{ include "override_config_map" . }}
{{- end -}}
{{- if .Values.Master.AdditionalConfig }}
{{- toYaml .Values.Master.AdditionalConfig | indent 2 }}
{{- end }}
