#!/usr/bin/env bash
# site/wp-config -- hardening flags in wp-config.php, set through wp-cli
#
# Only a small, well understood set is exposed. Editing wp-config.php by hand
# through a text parser is how sites get corrupted.
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 site_m_wpconfig)"

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
root=$(nv_site_get "$domain" root_path "$(site_domain_root "$domain")")
user=$(site_web_user "$domain")

[ -f "$root/wp-config.php" ] || { ui_err "$(t wp_update_not_wp)"; exit 2; }
[ -x /usr/local/bin/wp ] || { ui_err "$(t site_wp_nocli)"; exit 1; }
WP="sudo -u $user /usr/local/bin/wp --path=$root"

flag() { $WP config get "$1" --type=constant 2>/dev/null || echo '-'; }

ui_section "$(t wpc_hardening)"
ui_kv "DISALLOW_FILE_EDIT" "$(flag DISALLOW_FILE_EDIT)"
ui_kv "WP_DEBUG"           "$(flag WP_DEBUG)"
ui_kv "WP_DEBUG_DISPLAY"   "$(flag WP_DEBUG_DISPLAY)"
ui_kv "FORCE_SSL_ADMIN"    "$(flag FORCE_SSL_ADMIN)"
ui_kv "AUTOMATIC_UPDATER_DISABLED" "$(flag AUTOMATIC_UPDATER_DISABLED)"
ui_blank

ui_info "1) $(t wpc_harden)"
ui_info "2) $(t wpc_debug_off)"
ui_info "3) $(t wpc_force_ssl_admin)"
ui_info "0) $(t menu_back)"
ui_blank
printf '  %s: ' "$(t menu_prompt_short)"
read -r pick || exit 130

case $pick in
    0) exit 0 ;;
    1)
        $WP config set DISALLOW_FILE_EDIT true --raw --quiet 2>/dev/null
        $WP config set WP_DEBUG false --raw --quiet 2>/dev/null
        $WP config set WP_DEBUG_DISPLAY false --raw --quiet 2>/dev/null
        $WP config set WP_DEBUG_LOG true --raw --quiet 2>/dev/null
        msg="$(t wpc_harden_done)"
        ;;
    2)
        $WP config set WP_DEBUG false --raw --quiet 2>/dev/null
        $WP config set WP_DEBUG_DISPLAY false --raw --quiet 2>/dev/null
        msg="$(t wpc_debug_off_done)"
        ;;
    3)
        if [ ! -r "/etc/letsencrypt/live/$domain/fullchain.pem" ]; then
            ui_err "$(t sslforce_no_cert)"
            exit 1
        fi
        $WP config set FORCE_SSL_ADMIN true --raw --quiet 2>/dev/null
        msg="$(t wpc_force_ssl_done)"
        ;;
    *) ui_err "$(t menu_invalid)"; exit 2 ;;
esac

nv_trace wp-config "$domain option=$pick"
ui_ok "$msg"
ui_info "$(t wpc_reload_note)"
exit 0
