#!/usr/bin/env bash
# site/ssl-force -- redirect all plain HTTP traffic to HTTPS
#
# The flag is ignored (and reported) when the site has no certificate yet,
# because a redirect to a host without a working certificate locks visitors out.
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_sslforce)"

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
cur=$(nv_site_get "$domain" force_https 0)
ssl=$(nv_site_get "$domain" ssl none)
cert="/etc/letsencrypt/live/$domain/fullchain.pem"

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)"

if [ ! -r "$cert" ]; then
    ui_warn "$(t sslforce_no_cert)"
    ui_info "$(t sslforce_issue_hint)"
    exit 1
fi
ui_blank

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

new=$(site_toggle "$domain" force_https) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
[ "$new" = "1" ] && ui_ok "$(t sslforce_on)" || ui_ok "$(t sslforce_off)"
exit 0
