#!/usr/bin/env bash
# web/security-headers -- per-site response headers
#
# HSTS is added only when the site actually has a certificate, because sending
# it over plain HTTP would lock visitors out of the working address.
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_headers)"

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

ui_kv "$(t col_domain)" "$domain"
ui_kv "$(t col_ssl)"    "$ssl"
ui_kv "$(t web_state)"  "$([ "$cur" = "1" ] && t state_enabled || t state_disabled)"
ui_blank
ui_info "$(t web_headers_list)"
[ "$ssl" != "letsencrypt" ] && ui_warn "$(t web_hsts_needs_ssl)"
ui_blank

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

new=$(site_toggle "$domain" security_headers) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
[ "$new" = "1" ] && ui_ok "$(t web_headers_on)" || ui_ok "$(t web_headers_off)"
exit 0
