#!/usr/bin/env bash
# web/gzip -- compression level in the shared nginx snippet
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_gzip)"

cfg=/etc/nginx/conf.d/00-nhanhvps.conf
[ -f "$cfg" ] || { ui_err "$(t gzip_no_config)"; exit 1; }

cur=$(sed -n 's/^gzip_comp_level[[:space:]]*\([0-9]*\);/\1/p' "$cfg" | head -n 1)
ui_kv "$(t gzip_level)" "${cur:-off}"
ui_info "$(t gzip_scale)"
ui_blank

printf '  %s [%s]: ' "$(t gzip_prompt)" "${cur:-5}"
read -r level || exit 130
level=$(nv_trim "$level")
[ -z "$level" ] && exit 0
case $level in [1-9]) ;; *) ui_err "$(t gzip_bad)"; exit 2 ;; esac

nv_backup_path "$cfg" gzip >/dev/null 2>&1 || true
if grep -qE '^gzip_comp_level' "$cfg"; then
    sed -i -E "s|^gzip_comp_level.*|gzip_comp_level ${level};|" "$cfg"
else
    printf '\ngzip_comp_level %s;\n' "$level" >>"$cfg"
fi
[ "$level" -eq 1 ] && sed -i -E "s|^gzip on;|gzip off;|" "$cfg" || sed -i -E "s|^gzip off;|gzip on;|" "$cfg"

if nginx -t >/dev/null 2>&1; then
    svc_reload nginx
    nv_trace gzip "level=$level"
    ui_ok "$(t gzip_done "$level")"
else
    nv_backup_restore "$cfg" >/dev/null 2>&1 || true
    nv_fail 2201 "$(t site_fail_nginx)"
    exit 1
fi
exit 0
