#!/usr/bin/env bash
# onx-redis-sentinel-setup — Redis Sentinel konfigürasyonu
# Input:  {"master_name":"onox-master","master_host":"10.0.0.1","master_port":6379,"quorum":2}
# Output: {"configured":true,"sentinel_port":26379}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib/common.sh"

require_root
require_cmd redis-sentinel
require_cmd redis-cli
onx_json_input

MASTER_NAME="$(onx_json_field master_name 'onox-master')"
MASTER_HOST="$(onx_json_field master_host)"
MASTER_PORT="$(onx_json_field master_port '6379')"
QUORUM="$(onx_json_field quorum '2')"
SENTINEL_PORT="26379"
SENTINEL_CONF="/etc/redis/sentinel.conf"

[[ -z "$MASTER_HOST" ]] && onx_die 1 "master_host zorunlu"
[[ "$MASTER_PORT" =~ ^[0-9]+$ ]] || onx_die 1 "Gecersiz master_port: '${MASTER_PORT}'"
[[ "$QUORUM" =~ ^[0-9]+$ ]]      || onx_die 1 "Gecersiz quorum: '${QUORUM}'"

onx_log "redis-sentinel-setup: master=${MASTER_HOST}:${MASTER_PORT} quorum=${QUORUM}"

# Mevcut sentinel.conf yedeği
[[ -f "$SENTINEL_CONF" ]] && cp "$SENTINEL_CONF" "${SENTINEL_CONF}.bak.$(date +%s)"

cat > "$SENTINEL_CONF" <<SENTINEL
port ${SENTINEL_PORT}
daemonize yes
logfile /var/log/redis/sentinel.log
pidfile /var/run/redis-sentinel.pid

sentinel monitor ${MASTER_NAME} ${MASTER_HOST} ${MASTER_PORT} ${QUORUM}
sentinel down-after-milliseconds ${MASTER_NAME} 5000
sentinel failover-timeout ${MASTER_NAME} 60000
sentinel parallel-syncs ${MASTER_NAME} 1
SENTINEL

chown redis:redis "$SENTINEL_CONF" 2>/dev/null || true

# Sentinel servisini başlat/yeniden başlat
if systemctl is-enabled redis-sentinel &>/dev/null; then
    systemctl restart redis-sentinel || onx_die 3 "redis-sentinel yeniden başlatılamadı"
else
    systemctl enable --now redis-sentinel || onx_die 3 "redis-sentinel başlatılamadı"
fi

onx_log "redis-sentinel-setup: tamamlandi port=${SENTINEL_PORT}"
json_ok "{\"configured\":true,\"sentinel_port\":${SENTINEL_PORT},\"master_name\":\"${MASTER_NAME}\"}"
