#!/bin/bash
################################################################################
# Script Name: version/2.1.20/UPDATE.sh
# Description: Make BIND answer for the zones this panel gave it.
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################
#
# The panel has been writing zone files, including them from named.conf,
# validating them, reloading named and confirming the zone was loaded - and
# then printing the nameservers for the customer to set at their registrar.
# Every one of those steps was true. The zone still resolved for nobody.
#
# Nothing ever wrote named's options block, so it kept whatever the
# distribution shipped. On RHEL and its rebuilds that is:
#
#     listen-on port 53 { 127.0.0.1; };
#     allow-query     { localhost; };
#
# A nameserver that answers itself. This update rewrites those two settings,
# confines recursion to this machine so the server is not an open resolver
# (and so an install whose resolv.conf points at 127.0.0.1 keeps working),
# refuses zone transfers, reloads named and then asks the sockets whether
# anything actually changed.
#
# The original named configuration is kept beside itself as
# .hitechcloud-original, and a configuration named refuses is rolled back
# before named is asked to use it.
#
# Nothing here touches a firewall. A server whose port 53 is closed stays
# closed, and the check below will say so.
################################################################################

set -uo pipefail

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "[2.1.20] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[2.1.20] ${YELLOW}!${NC} $*" >&2; }
say()  { echo -e "[2.1.20] $*"; }

[[ $EUID -eq 0 ]] || { echo "[2.1.20] This update must run as root." >&2; exit 1; }

[[ -f /etc/hitechcloud/native/native.conf ]] || { say "not the native stack; nothing to do"; exit 0; }

if ! command -v named-checkconf >/dev/null 2>&1; then
    say "BIND is not installed on this server; nothing to do"
    exit 0
fi

if bash /usr/local/hitechcloudcli/native/dns.sh authoritative; then
    ok "named answers for its zones from off this machine"
else
    warn "named is still not reachable from outside. Check that port 53 is open"
    warn "in the firewall (TCP and UDP), then re-run: hitechcloudcli native-dns authoritative"
fi

ok "2.1.20 update complete"
exit 0
