#!/usr/bin/env bash
# web/request-limit -- per-site rate limiting using the shared zone
#
# The zone is declared once in /etc/nginx/conf.d/00-nhanhvps.conf; a site only
# opts in, which keeps the generated vhost free of bucket definitions.
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 web_m_ratelimit)"

if ! grep -qs 'zone=nv_site' /etc/nginx/conf.d/00-nhanhvps.conf; then
    ui_err "$(t web_ratelimit_no_zone)"
    ui_info "$(t web_ratelimit_zone_hint)"
    exit 1
fi

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
cur=$(nv_site_get "$domain" rate_limit 0)

ui_kv "$(t col_domain)" "$domain"
ui_kv "$(t web_state)"  "$([ "$cur" = "1" ] && t state_enabled || t state_disabled)"
ui_info "$(t web_ratelimit_desc)"
ui_blank

if [ "$cur" = "1" ]; then
    ui_confirm "$(t web_disable_q)" n || exit 0
else
    ui_warn "$(t web_ratelimit_warn)"
    ui_confirm "$(t web_enable_q)" n || exit 0
fi

new=$(site_toggle "$domain" rate_limit) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
[ "$new" = "1" ] && ui_ok "$(t web_ratelimit_on)" || ui_ok "$(t web_ratelimit_off)"
exit 0
