#!/usr/bin/env bash
# security/ddos -- per-site connection cap at the edge
#
# A connection limit stops a single host from occupying every PHP worker, which
# is what most cheap floods actually achieve.
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 sec_m_ddos)"

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

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

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

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

new=$(site_toggle "$domain" ddos_guard) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
[ "$new" = "1" ] && ui_ok "$(t sec_ddos_on)" || ui_ok "$(t sec_ddos_off)"
exit 0
