# yaml-language-server: $schema=./values.schema.json
image:
  repository: ghcr.io/ich777/steamcmd
  pullPolicy: IfNotPresent
  tag: palworld@sha256:2a2b86c3638a57d56d6c9e137e94e940b239ebf4e99a45ad460889e8c05edf19

securityContext:
  container:
    readOnlyRootFilesystem: false
    runAsUser: 0
    runAsGroup: 0

resources:
  limits:
    cpu: 4000m
    memory: 6000Mi
  requests:
    cpu: 400m
    memory: 1000Mi

service:
  main:
    ports:
      main:
        protocol: udp
        port: 8211
  api:
    enabled: true
    ports:
      api:
        enabled: true
        protocol: tcp
        port: 8212
  rcon:
    enabled: true
    ports:
      rcon:
        enabled: true
        protocol: tcp
        port: 25575
palworld:
  steam:
    id: "2394010"
    username: ""
    password: ""
    validate: false
  game:
    ServerName: "TrueCharts Palworld Server"
    ServerDescription: "A Palworld Server running in Kubernetes"
    ServerPassword: ""
    AdminPassword: "TrueChartsIsAHelmProject"
    bUseAuth: true
    # PublicIP: "my public IP"
    # AllowConnectPlatform: "Steam|Xbox"
  update_public_ip: false
  params:
    - -publiclobby
  params_extra:
    - -useperfthreads
    - -NoAsyncLoadingThread
    - -UseMultithreadForDS
  backup:
    enabled: true
    interval: 120
    to_keep: 12

workload:
  main:
    podSpec:
      initContainers:
        update-config-ini:
          enabled: true
          type: init
          imageSelector: "image"
          command:
            - /bin/sh
            - -c
          args:
            - |
                serverfiles={{ .Values.persistence.serverfiles.targetSelector.main.main.mountPath }}
                config=${serverfiles}/Pal/Saved/Config/LinuxServer
                cfgFile=${config}/PalWorldSettings.ini
                dfCfgFile=${serverfiles}/DefaultPalWorldSettings.ini

                mkdir -p ${config}
                if [ ! -f "${cfgFile}" ]; then
                    if [ -f "${dfCfgFile}" ]; then
                        echo "Default config file found, copying as cfgFile..."
                        cp "${dfCfgFile}" "${cfgFile}"
                    else
                        echo "Config file not found, fetching..."
                        # Fetch the config file if it doesn't exist, just like the container does
                        wget -qO "${cfgFile}" https://github.com/ich777/docker-steamcmd-server/raw/palworld/config/PalWorldSettings.ini
                    fi
                fi

                set_ini() {
                  local key="${1}"
                  local value="${2}"
                  local flags=""  # Initialize an empty string for flags

                  # Loop through arguments starting from the third one
                  for arg in "$@"; do
                      if [ "$arg" != "$key" ] && [ "$arg" != "$value" ]; then
                          flags="$flags $arg"  # Append each flag to the flags string
                      fi
                  done

                  # Check if the key exists in the OptionSettings section
                  if ! grep -q 'OptionSettings=(' "$cfgFile"; then
                      echo "OptionSettings section not found in '${cfgFile}'. Skipping..."
                      return
                  fi

                  # Check if the key exists within the OptionSettings section
                  if ! grep -q "${key}=" "$cfgFile"; then
                      echo "Key '${key}' does not exist in the OptionSettings section of '${cfgFile}'. Skipping..."
                      return
                  fi

                  # Iterate over flags
                  for flag in $flags; do
                      case $flag in
                          -q)
                              # Add quotes around the value
                              value="\"$value\""
                              ;;
                          -b)
                              # Handle boolean flag
                              if [ "$(echo "$value" | tr '[:upper:]' '[:lower:]')" = "true" ]; then
                                  value="True"
                              else
                                  value="False"
                              fi
                              ;;
                          *)
                              echo "Unknown flag: $flag. Skipping..."
                              ;;
                      esac
                  done

                  # Update the value within the OptionSettings section
                  sed -i "/OptionSettings=(/ {
                      :loop
                      /)$/! {
                          N
                          b loop
                      }
                      s|\(${key}=\)[^,]*|\1${value}|
                  }" "${cfgFile}"

                  # Check if the closing parenthesis is missing, and if so, add it
                  if ! grep -q ')$' "${cfgFile}"; then
                      sed -i "\|OptionSettings=(| s|$|)|" "${cfgFile}"
                  fi

                  echo "Set ${key} to ${value}"
                }

                echo "the following options are updating...."

                set_ini "RCONEnabled" "True" -b

                set_ini "RCONPort" "{{ .Values.service.rcon.ports.rcon.port }}"
                set_ini "PublicPort" "{{ .Values.service.main.ports.main.port }}"
                set_ini "RESTAPIEnabled" "True" -b
                set_ini "RESTAPIPort" "{{ .Values.service.api.ports.api.port }}"

                {{- range $key, $value := .Values.palworld.game }}
                  {{- $numRegex := "^[0-9]+([.][0-9]+)?$" -}}
                  {{- $boolRegex := "^(true|false)$" -}}
                  {{- $valueStr := toString $value -}}

                  {{- if (mustRegexMatch $numRegex $valueStr) }}
                    set_ini "{{ $key }}" {{ $value }}
                  {{- else if (mustRegexMatch $boolRegex (lower $valueStr)) }}
                    set_ini "{{ $key }}" {{ $valueStr | title }} -b
                  {{- else }}
                    set_ini "{{ $key }}" {{ quote $valueStr }} -q
                  {{- end }}
                {{- end }}
                echo "Done!"
      containers:
        main:
          probes:
            liveness:
              type: tcp
              port: "{{ .Values.service.rcon.ports.rcon.port }}"
            readiness:
              type: tcp
              port: "{{ .Values.service.rcon.ports.rcon.port }}"
            startup:
              type: tcp
              port: "{{ .Values.service.rcon.ports.rcon.port }}"
          env:
            # paths
            STEAMCMD_DIR: "{{ .Values.persistence.steamcmd.mountPath }}"
            SERVER_DIR: "{{ .Values.persistence.serverfiles.targetSelector.main.main.mountPath }}"
            # steam
            GAME_ID: "{{ .Values.palworld.steam.id }}"
            USERNAME: "{{ .Values.palworld.steam.username }}"
            PASSWRD: "{{ .Values.palworld.steam.password }}"
            VALIDATE: "{{ .Values.palworld.steam.validate }}"
            # game
            SRV_ADMIN_PWD: "{{ .Values.palworld.game.AdminPassword }}"
            UPDATE_PUBLIC_IP: "{{ .Values.palworld.update_public_ip }}"
            GAME_PARAMS: '{{ printf "-port=%v -publicport=%v -rconport=%v %s" .Values.service.main.ports.main.port .Values.service.main.ports.main.port .Values.service.rcon.ports.rcon.port (join " " .Values.palworld.params) }}'
            GAME_PARAMS_EXTRA: '{{ join " " .Values.palworld.params_extra }}'
            # backup
            BACKUP: "{{ .Values.palworld.backup.enabled }}"
            BACKUP_INTERVAL: "{{ .Values.palworld.backup.interval }}"
            BACKUP_TO_KEEP: "{{ .Values.palworld.backup.to_keep }}"

persistence:
  steamcmd:
    enabled: true
    mountPath: /serverdata/steamcmd
  serverfiles:
    enabled: true
    targetSelector:
      main:
        main:
          mountPath: /serverdata/serverfiles
        update-config-ini:
          mountPath: /serverdata/serverfiles
