#!/usr/bin/env bash
# cache/clear -- flush every cache layer in one deliberate action
#
# Used after changing a domain, deploying code, or when "the site shows the old
# version" — the three layers are Redis, opcache and the FPM workers.
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"

nv_require_root || exit 1
ui_header "$(t cache_m_clear)"

ui_section "$(t cache_layers)"
ui_kv "Redis" "$(redis-cli ping 2>/dev/null || echo stopped)"
mapfile -t vers < <(php_version_list)
for v in "${vers[@]}"; do
    ui_kv "opcache $v" "$(php"$v" -i 2>/dev/null | sed -n 's/^opcache.enable => \(.*\)/\1/p' | head -n 1)"
done

ui_blank
ui_warn "$(t cache_clear_warn)"
ui_confirm "$(t cache_clear_confirm)" n || { ui_info "$(t pf_cancelled)"; exit 0; }

if [ "$(redis-cli ping 2>/dev/null)" = "PONG" ]; then
    ui_step "$(t cache_clear_redis)"
    redis-cli flushall >/dev/null 2>&1 && ui_ok "$(t cache_cleared_redis)"
fi

for v in "${vers[@]}"; do
    ui_step "$(t cache_clear_opcache "$v")"
    php"$v" -d opcache.enable_cli=1 -r 'if(function_exists("opcache_reset")){opcache_reset();}' 2>/dev/null || true
    svc_reload "php$v-fpm" 2>/dev/null || true
    ui_ok "$(t cache_cleared_php "$v")"
done

nv_trace cache-clear "redis+opcache"
ui_blank
ui_ok "$(t cache_clear_done)"
exit 0
