#!/usr/bin/env bash
# security/csp -- Content-Security-Policy in report-only mode
#
# Enforcing CSP on an existing WordPress site breaks it. Report-only lets the
# operator watch violations for a week before switching anything on.
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_csp)"

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

ui_kv "$(t col_domain)" "$domain"
ui_kv "$(t web_state)"  "$([ "$cur" = "1" ] && t state_enabled || t state_disabled)"
ui_blank
ui_info "$(t csp_policy)"
ui_blank
ui_info "$(t csp_report_note)"
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" csp_report_only) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
[ "$new" = "1" ] && ui_ok "$(t csp_on)" || ui_ok "$(t csp_off)"
exit 0
