#!/usr/bin/env bash

# Copyright (c) 2021-2026 community-scripts ORG
# Author: pshankinclarke (lazarillo)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://valkey.io/

source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os

msg_info "Installing Valkey"
$STD apt update
$STD apt install -y valkey openssl
sed -i 's/^bind .*/bind 0.0.0.0/' /etc/valkey/valkey.conf

PASS="$(openssl rand -base64 48 | tr -dc 'a-zA-Z0-9' | head -c32)"
echo "requirepass $PASS" >>/etc/valkey/valkey.conf
echo "$PASS" >~/valkey.creds
chmod 600 ~/valkey.creds

MEMTOTAL_MB=$(free -m | grep ^Mem: | awk '{print $2}')
# reserve 25% of a node type's maxmemory value for system use
MAXMEMORY_MB=$((MEMTOTAL_MB * 75 / 100))

echo "" >>/etc/valkey/valkey.conf
echo "# Memory-optimized settings for small-scale deployments" >>/etc/valkey/valkey.conf
echo "maxmemory ${MAXMEMORY_MB}mb" >>/etc/valkey/valkey.conf
echo "maxmemory-policy allkeys-lru" >>/etc/valkey/valkey.conf
echo "maxmemory-samples 10" >>/etc/valkey/valkey.conf
msg_ok "Installed Valkey"

echo
read -r -p "${TAB3}Enable TLS for Valkey (Sentinel mode does not supported)? [y/N]: " prompt
if [[ ${prompt,,} =~ ^(y|yes)$ ]]; then
    read -r -p "${TAB3}Use TLS-only mode (disable TCP port 6379)? [y/N]: " tls_only
    msg_info "Configuring TLS for Valkey..."

    create_self_signed_cert "Valkey"
    TLS_DIR="/etc/ssl/valkey"
    TLS_CERT="$TLS_DIR/valkey.crt"
    TLS_KEY="$TLS_DIR/valkey.key"
    chown valkey:valkey "$TLS_CERT" "$TLS_KEY"

    if [[ ${tls_only,,} =~ ^(y|yes)$ ]]; then
        cat <<EOF >/etc/valkey/valkey.conf

# TLS configuration generated by Proxmox VE Valkey helper-script
port 0
tls-port 6379
tls-cert-file $TLS_DIR/valkey.crt
tls-key-file $TLS_DIR/valkey.key
tls-auth-clients no
EOF
        msg_ok "Enabled TLS-only mode on port 6379"
    else
        cat <<EOF >/etc/valkey/valkey.conf

# TLS configuration generated by Proxmox VE Valkey helper-script
tls-port 6380
tls-cert-file $TLS_DIR/valkey.crt
tls-key-file $TLS_DIR/valkey.key
tls-auth-clients no
EOF
        msg_ok "Enabled TLS on port 6380 and TCP on 6379"
    fi
fi

systemctl enable -q --now valkey-server
systemctl restart valkey-server

motd_ssh
customize
cleanup_lxc
