#!/usr/bin/env bash

set -Eeuo pipefail
umask 077

HOST=${REDIS5_HOST:-10.2.203.117}
PORT=${REDIS5_PORT:-6379}
DB=${REDIS5_DB:-0}
SECRET_FILE=${REDIS5_SECRET_FILE:-/etc/zhct/secrets/redis5.password}
AI_ENV=${AI_ENV:-/workspace/wwwroot/aizhct_sanquan/project/.env}
STORE_CONFIG=${STORE_CONFIG:-/workspace/wwwroot/zhct_sanquan/project/application/config/prod/zhct_sanquan/config.php}
MODE=live
case "${1:-}" in
    '') ;;
    --dry-run) MODE=dry-run ;;
    --config-only) MODE=config-only ;;
    *) echo "unknown argument: ${1:-}" >&2; exit 2 ;;
esac

[[ "$DB" == 0 ]] || { echo 'Redis5 database must be DB0' >&2; exit 1; }

if [[ "$MODE" == dry-run ]]; then
    printf 'would check Store and AI config plus Redis5 VIP %s:%s DB%s without logging its password\n' "$HOST" "$PORT" "$DB"
    exit 0
fi

[[ -r "$AI_ENV" ]] || { echo 'AI runtime env missing' >&2; exit 1; }
[[ -r "$STORE_CONFIG" ]] || { echo 'Store Redis config missing' >&2; exit 1; }
ai_redis=$(awk '/^\[REDIS\][[:space:]]*$/{show=1; next} /^\[/{if(show) exit} show{print}' "$AI_ENV")
grep -Eq '^HOSTNAME[[:space:]]*=[[:space:]]*10\.2\.203\.117[[:space:]]*$' <<<"$ai_redis"
grep -Eq '^HOSTPORT[[:space:]]*=[[:space:]]*6379[[:space:]]*$' <<<"$ai_redis"
if grep -Eq '^SELECT[[:space:]]*=' <<<"$ai_redis"; then
    grep -Eq '^SELECT[[:space:]]*=[[:space:]]*0[[:space:]]*$' <<<"$ai_redis" || { echo 'AI Redis database must be DB0 when SELECT is configured' >&2; exit 1; }
fi
store_redis=$(awk '/\$config\['\''redis'\''\][[:space:]]*=/{show=1} show{print} show && /^[[:space:]]*\];/{exit}' "$STORE_CONFIG")
grep -Eq "'host'[[:space:]]*=>[[:space:]]*'10\.2\.203\.117'" <<<"$store_redis"
grep -Eq "'port'[[:space:]]*=>[[:space:]]*6379" <<<"$store_redis"
if grep -Eq "'select'[[:space:]]*=>" <<<"$store_redis"; then
    grep -Eq "'select'[[:space:]]*=>[[:space:]]*0([,[:space:]]|$)" <<<"$store_redis" || { echo 'Store Redis database must be DB0 when select is configured' >&2; exit 1; }
fi

if [[ "$MODE" == config-only ]]; then
    echo 'PASS: Store and AI Redis5 config resolve to DB0 (implicit default or explicit 0)'
    exit 0
fi

[[ -x /opt/redis-client/5.0.14/bin/redis-cli || -x /usr/bin/redis-cli ]] || { echo 'redis-cli missing' >&2; exit 1; }
CLI=$(command -v redis-cli || true)
[[ -n "$CLI" ]] || CLI=/opt/redis-client/5.0.14/bin/redis-cli
[[ -r "$SECRET_FILE" ]] || { echo 'Redis5 secret file missing' >&2; exit 1; }
export REDISCLI_AUTH
REDISCLI_AUTH=$(<"$SECRET_FILE")
[[ "$($CLI -h "$HOST" -p "$PORT" -n "$DB" PING)" == PONG ]]
key="zhct_sanquan:runtime-check:$(hostname -s):$$"
$CLI -h "$HOST" -p "$PORT" -n "$DB" SET "$key" ok EX 30 NX >/dev/null
[[ "$($CLI -h "$HOST" -p "$PORT" -n "$DB" GET "$key")" == ok ]]
$CLI -h "$HOST" -p "$PORT" -n "$DB" DEL "$key" >/dev/null
unset REDISCLI_AUTH
echo 'PASS: Redis5 VIP and DB0 read/write'
