#!/usr/bin/env bash
# system/service-control -- start, stop, restart or reload one service
#
# Separate from system/services (the read-only board) so that browsing status
# can never accidentally stop production.
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 sys_m_servicecontrol)"

mapfile -t svcs < <(printf '%s\n' nginx php8.3-fpm mariadb redis-server fail2ban cron | sort)
i=0
for s in "${svcs[@]}"; do
    i=$((i + 1))
    printf '  %2d) %-18s %s\n' "$i" "$s" "$(svc_status_word "$s" 2>/dev/null || echo missing)"
done
printf '  %2d) %s\n' 0 "$(t menu_back)"
ui_blank

printf '  %s: ' "$(t svc_pick)"
read -r pick || exit 130
case $pick in ''|*[!0-9]*) ui_err "$(t ui_invalid_number)"; exit 2 ;; esac
[ "$pick" -eq 0 ] && exit 0
[ "$pick" -lt 1 ] || [ "$pick" -gt ${#svcs[@]} ] && { ui_err "$(t menu_invalid)"; exit 2; }
svc=${svcs[$((pick - 1))]}

ui_info "1) start  2) stop  3) restart  4) reload  0) $(t menu_back)"
printf '  %s: ' "$(t menu_prompt_short)"
read -r act || exit 130
case $act in
    0) exit 0 ;;
    1) op=start ;;
    2) op=stop ;;
    3) op=restart ;;
    4) op=reload ;;
    *) ui_err "$(t menu_invalid)"; exit 2 ;;
esac

if [ "$op" = "stop" ]; then
    ui_warn "$(t svc_stop_warn "$svc")"
    ui_confirm "$(t svc_stop_q "$svc")" n || exit 0
fi

if "svc_$op" "$svc"; then
    sleep 1
    nv_trace service "$op $svc"
    ui_ok "$(t svc_done "$svc" "$op")"
    ui_kv "$(t svc_state)" "$(svc_status_word "$svc" 2>/dev/null || echo unknown)"
else
    nv_fail 6108 "$(t svc_failed "$svc" "$op")"
    exit 1
fi
exit 0
