#!/bin/bash
################################################################################
# Script Name: version/3.0.5/UPDATE.sh
# Description: Apply version 3.0.5 migrations: re-render every zone so an
#              account's further addresses (user-ip --add) land in DNS, and
#              re-apply the mirror's directory-listing rule where this host
#              serves the mirror.
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################

set -uo pipefail
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "[3.0.5] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.0.5] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.0.5] This update must run as root." >&2; exit 1; }

[ -f /etc/hitechcloud/native/native.conf ] || { ok "3.0.5 update steps completed (container architecture)"; exit 0; }

# 1. Every account's zones get an A/AAAA for each address it holds. Cheap
#    for an account with one address (the records come out the same).
if [ -x /usr/local/hitechcloudcli/native/dns.sh ]; then
    for f in /etc/hitechcloud/hitechcloud/core/users/*/ip.json; do
        [ -f "$f" ] || continue
        user=$(basename "$(dirname "$f")")
        for d in $(hitechcloudcli domains-user "$user" 2>/dev/null | grep -oE '^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$'); do
            bash /usr/local/hitechcloudcli/native/dns.sh set-address "$d" --user "$user" >/dev/null 2>&1 || warn "$d: zone not re-rendered"
        done
    done
    ok "DNS zones carry every address their account holds"
fi

# 2. The mirror, where this host serves one: directory listing for the
#    allowed addresses only.
if [ -f /etc/hitechcloud/native/frontend/conf.d/mirrors.*.conf ] && [ -f /opt/hitechcloud/deploy/install-mirror.sh ]; then
    bash /opt/hitechcloud/deploy/install-mirror.sh >/dev/null 2>&1 && ok "Mirror directory listing restricted to MIRROR_INDEX_ALLOW" || warn "install-mirror.sh reported errors"
fi

ok "3.0.5 update steps completed successfully"
exit 0
