#!/bin/bash
# Least-privilege root wrapper for updating system hostname, /etc/hosts, system timezone,
# and NTP (systemd-timesyncd / chrony) configuration & clock synchronization safely.
# Compatible with systemd ProtectSystem=strict where /etc is read-only and /etc/hosts is file-bind-mounted.
set -euo pipefail

usage() {
    echo "Usage: $0 {set-hostname <hostname>|set-timezone <timezone>|set-ntp <on|off> [csv_servers]|sync-ntp}" >&2
    exit 1
}

[ $# -ge 1 ] || usage
ACTION="$1"

validate_ntp_host() {
    local host="$1"
    # Strict RFC-1123 hostname, IPv4, or IPv6 literal (no spaces, quotes, or shell metacharacters)
    if [[ "$host" =~ ^[a-zA-Z0-9]([a-zA-Z0-9.-]{0,251}[a-zA-Z0-9])?$ ]] && [[ "$host" != *".."* ]]; then
        return 0
    fi
    if [[ "$host" =~ ^[0-9a-fA-F:]{2,45}$ ]] && [[ "$host" == *:* ]]; then
        return 0
    fi
    return 1
}

print_time_status() {
    local tz ntp_active synced server utc_now
    tz="$(timedatectl show --property=Timezone --value 2>/dev/null || cat /etc/timezone 2>/dev/null || echo 'UTC')"
    ntp_active="$(timedatectl show --property=NTP --value 2>/dev/null || echo 'no')"
    synced="$(timedatectl show --property=NTPSynchronized --value 2>/dev/null || echo 'no')"
    server=""
    if command -v timedatectl >/dev/null 2>&1; then
        server="$(timedatectl timesync-status 2>/dev/null | awk -F': ' '/^[[:space:]]*Server:/ {print $2; exit}' | tr -d '\r' || true)"
    fi
    if [ -z "$server" ] && command -v chronyc >/dev/null 2>&1; then
        server="$(chronyc tracking 2>/dev/null | awk -F': ' '/^Reference ID/ {print $2; exit}' | tr -d '\r' || true)"
    fi
    utc_now="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
    printf 'TIMEZONE=%s\n' "$tz"
    printf 'NTP_ACTIVE=%s\n' "$ntp_active"
    printf 'SYNCED=%s\n' "$synced"
    printf 'NTP_SERVER=%s\n' "$server"
    printf 'UTC_TIME=%s\n' "$utc_now"
}

case "$ACTION" in
    set-hostname)
        [ $# -eq 2 ] || usage
        NEW_HOST="$2"
        # Strict RFC-1123 hostname validation (no leading '-', spaces, slashes, or sed metacharacters)
        if [[ ! "$NEW_HOST" =~ ^[a-zA-Z0-9]([a-zA-Z0-9.-]{0,251}[a-zA-Z0-9])?$ ]] || [[ "$NEW_HOST" == *".."* ]]; then
            echo "Invalid hostname: $NEW_HOST" >&2
            exit 2
        fi

        hostnamectl set-hostname -- "$NEW_HOST"

        TMP_HOSTS=$(mktemp /tmp/hosts.XXXXXX)
        trap 'rm -f "$TMP_HOSTS"' EXIT

        if grep -qE '^127\.0\.1\.1[[:space:]]' /etc/hosts; then
            awk -v host="$NEW_HOST" '
                /^127\.0\.1\.1[[:space:]]/ { print "127.0.1.1\t" host; next }
                { print }
            ' /etc/hosts > "$TMP_HOSTS"
        else
            cat /etc/hosts > "$TMP_HOSTS"
            printf '127.0.1.1\t%s\n' "$NEW_HOST" >> "$TMP_HOSTS"
        fi

        # Overwrite /etc/hosts in-place so systemd ProtectSystem=strict bind-mount on /etc/hosts is preserved
        cat "$TMP_HOSTS" > /etc/hosts
        chmod 0644 /etc/hosts 2>/dev/null || true
        rm -f "$TMP_HOSTS"
        trap - EXIT
        ;;
    set-timezone)
        [ $# -eq 2 ] || usage
        NEW_TZ="$2"
        if [[ ! "$NEW_TZ" =~ ^(UTC|Etc/GMT([+-][0-9]{1,2})?|[A-Za-z_]{2,32}(/[A-Za-z0-9_+.-]{1,64}){1,2})$ ]]; then
            echo "Invalid timezone: $NEW_TZ" >&2
            exit 2
        fi
        timedatectl set-timezone -- "$NEW_TZ"
        print_time_status
        ;;
    set-ntp)
        [ $# -ge 2 ] && [ $# -le 3 ] || usage
        RAW_ENABLED="$2"
        RAW_SERVERS="${3:-}"

        case "$RAW_ENABLED" in
            on|true|1|yes)  NTP_BOOL="true" ;;
            off|false|0|no) NTP_BOOL="false" ;;
            *) echo "Invalid NTP state: $RAW_ENABLED" >&2; exit 2 ;;
        esac

        VALID_SERVERS=()
        if [ -n "$RAW_SERVERS" ]; then
            IFS=',' read -r -a CANDIDATES <<< "$RAW_SERVERS"
            for entry in "${CANDIDATES[@]}"; do
                trimmed="${entry#"${entry%%[![:space:]]*}"}"
                trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
                [ -z "$trimmed" ] && continue
                if ! validate_ntp_host "$trimmed"; then
                    echo "Invalid NTP server: $trimmed" >&2
                    exit 2
                fi
                VALID_SERVERS+=("$trimmed")
                [ "${#VALID_SERVERS[@]}" -ge 6 ] && break
            done
        fi

        if [ "${#VALID_SERVERS[@]}" -gt 0 ]; then
            if [ ! -d /etc/systemd/timesyncd.conf.d ]; then
                if ! mkdir -p /etc/systemd/timesyncd.conf.d 2>/dev/null; then
                    echo "Unable to create /etc/systemd/timesyncd.conf.d (read-only filesystem). Ensure directory exists and restart service." >&2
                    exit 1
                fi
                chmod 0755 /etc/systemd/timesyncd.conf.d 2>/dev/null || true
            fi
            NTP_LINE="${VALID_SERVERS[*]}"
            if ! cat > /etc/systemd/timesyncd.conf.d/ring2all-ntp.conf <<EOF
# Managed by Ring2All System Misc
[Time]
NTP=${NTP_LINE}
FallbackNTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 3.debian.pool.ntp.org
EOF
            then
                echo "Unable to write /etc/systemd/timesyncd.conf.d/ring2all-ntp.conf (read-only filesystem)." >&2
                exit 1
            fi
            chmod 0644 /etc/systemd/timesyncd.conf.d/ring2all-ntp.conf 2>/dev/null || true
        fi

        timedatectl set-ntp "$NTP_BOOL" 2>/dev/null || true
        if [ "$NTP_BOOL" = "true" ]; then
            if systemctl is-active --quiet chrony 2>/dev/null || systemctl is-active --quiet chronyd 2>/dev/null; then
                systemctl reload-or-restart chrony 2>/dev/null || systemctl reload-or-restart chronyd 2>/dev/null || true
            elif systemctl list-unit-files systemd-timesyncd.service >/dev/null 2>&1; then
                systemctl restart systemd-timesyncd 2>/dev/null || true
            fi
        fi
        print_time_status
        ;;
    sync-ntp)
        [ $# -eq 1 ] || usage
        timedatectl set-ntp true 2>/dev/null || true
        if command -v chronyc >/dev/null 2>&1 && (systemctl is-active --quiet chrony 2>/dev/null || systemctl is-active --quiet chronyd 2>/dev/null); then
            chronyc -a makestep >/dev/null 2>&1 || true
        elif systemctl list-unit-files systemd-timesyncd.service >/dev/null 2>&1; then
            systemctl restart systemd-timesyncd 2>/dev/null || true
            for _ in 1 2 3 4 5; do
                if [ "$(timedatectl show --property=NTPSynchronized --value 2>/dev/null || echo no)" = "yes" ]; then
                    break
                fi
                sleep 0.3
            done
        fi
        print_time_status
        ;;
    *)
        usage
        ;;
esac
