#!/usr/bin/env bash
# cache/status -- Redis and opcache side by side, read-only
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

ui_header "$(t cache_m_status)"

ui_section "Redis"
if [ "$(redis-cli ping 2>/dev/null)" = "PONG" ]; then
    info=$(redis-cli info 2>/dev/null | tr -d '\r')
    val() { printf '%s' "$info" | sed -n "s/^$1://p" | head -n 1; }
    ui_ok "$(t col_status)"
    ui_kv "$(t cache_redis_version)" "$(val redis_version)"
    ui_kv "$(t cache_redis_memory)"  "$(val used_memory_human) / $(val maxmemory_human)"
    ui_kv "$(t cache_redis_keys)"    "$(redis-cli dbsize 2>/dev/null)"
else
    ui_warn "$(t redis_down)"
fi

ui_section "opcache"
mapfile -t vers < <(php_version_list)
if [ ${#vers[@]} -eq 0 ]; then
    ui_info "$(t php_none_installed)"
else
    for v in "${vers[@]}"; do
        st=$(php"$v" -d opcache.enable_cli=1 -r \
            'if(function_exists("opcache_get_status")){$s=@opcache_get_status(false);
              if($s){printf("%d %d %d",$s["opcache_statistics"]["hits"],
                $s["opcache_statistics"]["misses"],$s["opcache_statistics"]["num_cached_scripts"]);}}' \
            2>/dev/null)
        if [ -n "$st" ]; then
            read -r h m s2 <<<"$st"
            tot=$((h + m)); rate=0; [ "$tot" -gt 0 ] && rate=$((h * 100 / tot))
            ui_kv "PHP $v" "$(t cache_opcache_line "$rate" "$s2")"
        else
            ui_kv "PHP $v" "$(t php_opcache_unavailable)"
        fi
    done
fi

ui_section "$(t cache_sites)"
if [ "$(nv_site_count)" -eq 0 ]; then
    ui_info "$(t site_none)"
else
    for d in $(nv_site_list); do
        [ "$(nv_site_get "$d" cache_redis 0)" = "1" ] \
            && ui_ok "$d $(t cache_site_on)" || ui_info "$d $(t cache_site_off)"
    done
fi
ui_blank
exit 0
