#!/usr/bin/env bash
# php/opcache -- hit rate and a safe reset
#
# Reading status needs opcache.enable_cli or a status script; when it is not
# available the module says so instead of printing zeros.
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 php_m_opcache)"

v=${1:-$(php_default_version)}
ui_kv "$(t php_col_version)" "$v"

enabled=$(php"$v" -i 2>/dev/null | sed -n 's/^opcache.enable => \(.*\)/\1/p' | head -n 1)
ui_kv "opcache.enable" "${enabled:-unknown}"

status=$(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 "$status" ]; then
    read -r hits misses scripts <<<"$status"
    total=$((hits + misses))
    rate=0
    [ "$total" -gt 0 ] && rate=$(( hits * 100 / total ))
    ui_kv "$(t php_opcache_hits)"   "$hits"
    ui_kv "$(t php_opcache_misses)" "$misses"
    ui_kv "$(t php_opcache_rate)"   "$rate%"
    ui_kv "$(t php_opcache_scripts)" "$scripts"
else
    ui_warn "$(t php_opcache_unavailable)"
fi

ui_blank
if ui_confirm "$(t php_opcache_reset_q "$v")" n; then
    if php"$v" -d opcache.enable_cli=1 -r 'exit(function_exists("opcache_reset") && opcache_reset() ? 0 : 1);' 2>/dev/null; then
        ui_ok "$(t php_opcache_reset_cli)"
    fi
    # the CLI reset does not touch the FPM workers, so reload them too
    svc_reload "php$v-fpm"
    nv_trace php-opcache "reset $v"
    ui_ok "$(t php_opcache_reset_done)"
fi
exit 0
