{{- $myNS := lookup "v1" "Namespace" "" .Release.Namespace }}
{{- $host := index $myNS.metadata.annotations "namespace.cozystack.io/host" }}
{{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-vpn" .Release.Name) }}
{{- $accessKeys := list }}
{{- $passwords := dict }}
{{- if and (hasKey $existingSecret "data") (hasKey $existingSecret.data "shadowbox_config.json") }}
  {{- $config := index $existingSecret.data "shadowbox_config.json" }}
  {{- $accessKeys = index (fromJson (b64dec $config)) "accessKeys" }}
{{- end }}
{{- range $accessKeys }}
  {{- $_ := set $passwords .name .password }}
{{- end }}
{{- range $user, $u := .Values.users }}
  {{- if $u.password }}
    {{- $_ := set $passwords $user $u.password }}
  {{- else if not (index $passwords $user) }}
    {{- $_ := set $passwords $user (randAlphaNum 16) }}
  {{- end }}
{{- end }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Release.Name }}-vpn
type: Opaque
stringData:
  shadowbox_server_config.json: |
    {
      "rollouts": [
        {
          "id": "single-port",
          "enabled": true
        }
      ],
      "portForNewAccessKeys": 40000,
      "hostname": "localhost"
    }
  shadowbox_config.json: |
    {
      "accessKeys": [
        {{- $c := 1 | int }}
        {{- range $user, $u := .Values.users }}
        {{- if ne $c 1 }},{{ end }}
        {
          "id": "{{ $c }}",
          "metricsId": "{{ $user }}",
          "name": "{{ $user }}",
          "password": "{{ index $passwords $user }}",
          "port": 40000,
          "encryptionMethod": "chacha20-ietf-poly1305"
        }
        {{- $c = add1 $c }}
        {{- end }}
      ],
      "nextId": {{ $c }}
    }
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Release.Name }}-urls
type: Opaque
foo: |
  {{ toJson $passwords }}
stringData:
  {{- range $user, $u := .Values.users }}
  "{{ $user }}": "ss://{{ regexReplaceAll "=" (replace "/" "_" (replace "+" "-" (printf "chacha20-ietf-poly1305:%s" (index $passwords $user) | b64enc))) "" }}@{{ $.Values.host | default (printf "%s.%s" $.Release.Name $host) }}:40000/?outline=1#{{ $.Release.Name }}"
  {{- end }}
