apiVersion: v1
kind: ConfigMap
metadata:
  name: postiz-valkey-init-scripts
  labels:
    helm.sh/chart: valkey-0.9.4
    app.kubernetes.io/name: valkey
    app.kubernetes.io/instance: postiz
    app.kubernetes.io/version: "9.1.0"
    app.kubernetes.io/managed-by: Helm
data:
  init.sh: |-
    #!/bin/sh
    set -eu

    # Default config paths
    VALKEY_CONFIG=${VALKEY_CONFIG_PATH:-/data/conf/valkey.conf}

    LOGFILE="/data/init.log"
    DATA_DIR="/data/conf"

    # Logging function (outputs to stderr and file)
    log() {
      echo "$(date) $1" | tee -a "$LOGFILE" >&2
    }
    # Function to get password for a user
    # Usage: get_user_password <username> [password_key]
    # Returns: password via stdout, exits with error if not found
    get_user_password() {
      username="$1"
      password_key="${2:-$username}"
      password=""
      # Try to get password from existing secret first (priority)
      if [ -f "/valkey-users-secret/$password_key" ]; then
        password=$(cat "/valkey-users-secret/$password_key")
        log "Using password from existing secret for user $username"
      elif [ -f "/valkey-auth-secret/${username}-password" ]; then
        # Fallback to inline password
        password=$(cat "/valkey-auth-secret/${username}-password")
        log "Using inline password for user $username"
      else
        log "ERROR: No password found for user $username"
        return 1
      fi

      echo "$password"
    }

    # Clean old log if requested
    if [ "${KEEP_OLD_LOGS:-false}" != "true" ]; then
      rm -f "$LOGFILE"
    fi

    if [ -f "$LOGFILE" ]; then
      log "Detected restart of this instance ($HOSTNAME)"
    fi

    log "Creating configuration in $DATA_DIR..."
    mkdir -p "$DATA_DIR"
    rm -f "$VALKEY_CONFIG"


    # Base valkey.conf
    log "Generating base valkey.conf"
    {
      echo "port 6379"
      echo "protected-mode no"
      echo "bind * -::*"
      echo "dir /data"
    } >>"$VALKEY_CONFIG"
    # Create secure directory for ACL file
    log "Creating /etc/valkey directory for ACL file"
    mkdir -p /etc/valkey

    # Set aclfile path in valkey.conf
    echo "aclfile /etc/valkey/users.acl" >>"$VALKEY_CONFIG"

    # Remove or reset existing ACL file if present (it may be read-only from previous run)
    log "Preparing ACL file at /etc/valkey/users.acl"
    if [ -f /etc/valkey/users.acl ]; then
      log "Removing existing read-only users.acl file"
      chmod 0600 /etc/valkey/users.acl
      rm -f /etc/valkey/users.acl
    fi

    # Create ACL file with secure permissions
    touch /etc/valkey/users.acl
    chmod 0600 /etc/valkey/users.acl
    # Generate ACL entries for each user
    log "Generating ACL entries for users"

    # User: default
    PASSWORD=$(get_user_password "default" "default") || exit 1

    # Hash the password and write ACL entry
    PASSHASH=$(echo -n "$PASSWORD" | sha256sum | cut -f 1 -d " ")
    echo "user default on #$PASSHASH ~* &* +@all" >> /etc/valkey/users.acl

    # Set final permissions
    chmod 0400 /etc/valkey/users.acl
    log "ACL file created with 0400 permissions"
    # Replica mode configuration
    log "Configuring replication mode"

    # Use POD_INDEX from Kubernetes metadata
    POD_INDEX=${POD_INDEX:-0}
    IS_MASTER=false

    # Check if this is pod-0 (master)
    if [ "$POD_INDEX" = "0" ]; then
      IS_MASTER=true
      log "This pod (index $POD_INDEX) is configured as MASTER"
    else
      log "This pod (index $POD_INDEX) is configured as REPLICA"
    fi

    # Configure replica settings
    if [ "$IS_MASTER" = "false" ]; then
      MASTER_HOST="postiz-valkey-0.postiz-valkey-headless.postiz.svc.cluster.local"
      MASTER_PORT="6379"

      log "Configuring replica to follow master at $MASTER_HOST:$MASTER_PORT"

      {
        echo ""
        echo "# Replica Configuration"
        echo "replicaof $MASTER_HOST $MASTER_PORT"
        echo "replica-announce-ip postiz-valkey-$POD_INDEX.postiz-valkey-headless.postiz.svc.cluster.local"
        echo ""
        echo "# Master authentication"
      } >>"$VALKEY_CONFIG"
      # Get the password for the replication user
      REPL_PASSWORD=$(get_user_password "default" "default") || exit 1

      # Write masterauth configuration
      echo "masterauth $REPL_PASSWORD" >>"$VALKEY_CONFIG"
      echo "masteruser default" >>"$VALKEY_CONFIG"
      log "Configured masterauth with user default"
    fi

    # Append extra configs if present
    if [ -f /usr/local/etc/valkey/valkey.conf ]; then
      log "Appending /usr/local/etc/valkey/valkey.conf"
      cat /usr/local/etc/valkey/valkey.conf >>"$VALKEY_CONFIG"
    fi
    if [ -d /extravalkeyconfigs ]; then
      log "Appending files in /extravalkeyconfigs/"
      cat /extravalkeyconfigs/* >>"$VALKEY_CONFIG"
    fi
