#!/usr/bin/env bash
# php/versions -- installed version inventory and the CLI default
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_versions)"

mapfile -t versions < <(php_version_list)
if [ ${#versions[@]} -eq 0 ]; then
    ui_warn "$(t php_none_installed)"
    ui_info "$(t php_install_hint)"
    exit 0
fi

default=$(php_default_version)
printf '  %-10s %-14s %-12s %s\n' \
    "$(t php_col_version)" "$(t php_col_cli)" "$(t svc_state)" "$(t php_col_sites)"
for v in "${versions[@]}"; do
    cli=$(php"$v" -v 2>/dev/null | head -n 1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo '-')
    state=$(svc_status_word "php$v-fpm" 2>/dev/null || echo missing)
    sites=0
    for d in $(nv_site_list); do
        [ "$(nv_site_get "$d" php_version "")" = "$v" ] && sites=$((sites + 1))
    done
    mark=''
    [ "$v" = "$default" ] && mark=' *'
    printf '  %-10s %-14s %-12s %s%s\n' "$v" "$cli" "$state" "$sites" "$mark"
done

ui_blank
ui_kv "$(t php_default_version)" "$default"
ui_info "$(t php_default_note)"
ui_blank
exit 0
