{{- if not (kindIs "string" .Values.githubConfigSecret) }}
{{- $hasCustomResourceMeta := (and .Values.resourceMeta .Values.resourceMeta.githubConfigSecret) }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "gha-runner-scale-set.githubsecret" . }}
  namespace: {{ include "gha-runner-scale-set.namespace" . }}
  labels:
    {{- $base := include "gha-runner-scale-set.labels" . | fromYaml }}
    {{- $extra := dict "app.kubernetes.io/component" "" }}
    {{- $reserved := merge $base $extra }}
    {{- with .Values.labels }}
    {{- range $k, $v := . }}
    {{- if not (or (hasKey $reserved $k) (hasPrefix "actions.github.com/" $k)) }}
    {{ $k }}: {{ $v | quote }}
    {{- end }}
    {{- end }}
    {{- end }}
    {{- if $hasCustomResourceMeta }}
    {{- with .Values.resourceMeta.githubConfigSecret.labels }}
    {{- toYaml . | nindent 4 }}
    {{- end }}
    {{- end }}
    {{- include "gha-runner-scale-set.labels" . | nindent 4 }}
  annotations:
    {{- with .Values.annotations }}
    {{- toYaml . | nindent 4 }}
    {{- end }}
    {{- if $hasCustomResourceMeta }}
    {{- with .Values.resourceMeta.githubConfigSecret.annotations }}
    {{- toYaml . | nindent 4 }}
    {{- end }}
    {{- end }}
  finalizers:
    - actions.github.com/cleanup-protection
data:
  {{- $hasToken := false }}
  {{- $hasAppId := false }}
  {{- $hasInstallationId := false }}
  {{- $hasPrivateKey := false }}
  {{- range $secretName, $secretValue := (required "Values.githubConfigSecret is required for setting auth with GitHub server." .Values.githubConfigSecret) }}
    {{- if $secretValue }}
  {{ $secretName }}: {{ $secretValue | toString | b64enc }}
      {{- if eq $secretName "github_token" }}
        {{- $hasToken = true }}
      {{- end }}
      {{- if eq $secretName "github_app_id" }}
        {{- $hasAppId = true }}
      {{- end }}
      {{- if eq $secretName "github_app_installation_id" }}
        {{- $hasInstallationId = true }}
      {{- end }}
      {{- if eq $secretName "github_app_private_key" }}
        {{- $hasPrivateKey = true }}
      {{- end }}
    {{- end }}
  {{- end }}
  {{- if and (not $hasToken) (not ($hasAppId)) }}
    {{- fail "A valid .Values.githubConfigSecret is required for setting auth with GitHub server, provide .Values.githubConfigSecret.github_token or .Values.githubConfigSecret.github_app_id." }}
  {{- end }}
  {{- if and $hasAppId (or (not $hasInstallationId) (not $hasPrivateKey)) }}
    {{- fail "A valid .Values.githubConfigSecret is required for setting auth with GitHub server, provide .Values.githubConfigSecret.github_app_installation_id and .Values.githubConfigSecret.github_app_private_key." }}
  {{- end }}
{{- end}}
