#!/bin/sh /etc/rc.common
# Copyright (C) 2026 OpenWrt.org

START=95
STOP=10

USE_PROCD=1

PROG=/usr/bin/valkey-server
CONF=/etc/valkey/valkey.conf

validate_valkey_section() {
	uci_validate_section valkey instance "${1}" \
		'enabled:bool:1' \
		'port:port:6379' \
		'bind:host:127.0.0.1' \
		'dir:directory:/var/lib/valkey' \
		'logfile:string:/var/log/valkey.log' \
		'daemonize:bool:0' \
		'maxmemory:string' \
		'maxmemory_policy:string' \
		'save:list(string)' \
		'appendonly:bool:0' \
		'appendfilename:string:appendonly.aof'
}

valkey_instance() {
	local cfg="$1"
	local enabled port bind dir logfile daemonize maxmemory maxmemory_policy save appendonly appendfilename

	validate_valkey_section "${cfg}" || {
		echo "validation failed"
		return 1
	}

	[ "${enabled}" = "0" ] && return 0

	# Create necessary directories
	mkdir -p "${dir}"
	mkdir -p "$(dirname ${logfile})"

	# Generate runtime config
	local config_file="/var/etc/valkey-${cfg}.conf"
	mkdir -p /var/etc

	# Start with base config if exists
	if [ -f "$CONF" ]; then
		grep -v "^port\|^bind\|^dir\|^logfile\|^daemonize\|^maxmemory\|^save\|^appendonly\|^appendfilename" "$CONF" > "$config_file"
	else
		> "$config_file"
	fi

	# Add runtime configuration
	cat >> "$config_file" <<-EOF
		port ${port}
		bind ${bind}
		dir ${dir}
		logfile ${logfile}
		daemonize no
	EOF

	# Add optional settings
	[ -n "${maxmemory}" ] && echo "maxmemory ${maxmemory}" >> "$config_file"
	[ -n "${maxmemory_policy}" ] && echo "maxmemory-policy ${maxmemory_policy}" >> "$config_file"

	# Add save directives
	if [ -n "${save}" ]; then
		for save_rule in ${save}; do
			echo "save ${save_rule}" >> "$config_file"
		done
	fi

	# Add append-only file settings
	if [ "${appendonly}" = "1" ]; then
		echo "appendonly yes" >> "$config_file"
		[ -n "${appendfilename}" ] && echo "appendfilename ${appendfilename}" >> "$config_file"
	fi

	procd_open_instance
	procd_set_param command "$PROG" "$config_file"
	procd_set_param file "$config_file"
	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param user valkey
	procd_close_instance
}

start_service() {
	# Create valkey user if it doesn't exist
	user_exists valkey || user_add valkey 450 450 "Valkey" /var/lib/valkey /bin/false

	config_load 'valkey'
	config_foreach valkey_instance 'instance'
}

service_triggers() {
	procd_add_reload_trigger "valkey"
	procd_add_validation validate_valkey_section
}

stop_service() {
	# Clean up any leftover socket files
	rm -f /tmp/valkey*.sock
}
