#!/bin/bash
# ==============================================================================
# karch module: timezone
# Phase 2 (chroot) — Set timezone, hardware clock, and hostname
# ==============================================================================

run_timezone() {
    # --- Timezone selection --------------------------------------------------
    msg_info "Configuring timezone..."

    # Build region list from /usr/share/zoneinfo
    local regions=()
    while IFS= read -r region; do
        regions+=("$region" "")
    done < <(find /usr/share/zoneinfo -mindepth 1 -maxdepth 1 -type d \
        ! -name 'posix' ! -name 'right' -printf '%f\n' | sort)

    local region
    region=$(dialog_menu "Timezone — Region" \
        "Select your region:" \
        "${regions[@]}") || return 1

    # Build city list for the selected region
    local cities=()
    while IFS= read -r city; do
        cities+=("$city" "")
    done < <(find "/usr/share/zoneinfo/${region}" -mindepth 1 -maxdepth 1 -printf '%f\n' | sort)

    # Some regions (e.g. UTC) have no sub-entries — handle gracefully
    local timezone
    if [[ ${#cities[@]} -eq 0 ]]; then
        timezone="$region"
    else
        local city
        city=$(dialog_menu "Timezone — City" \
            "Select your city/area in ${region}:" \
            "${cities[@]}") || return 1
        timezone="${region}/${city}"
    fi

    # Apply timezone
    ln -sf "/usr/share/zoneinfo/${timezone}" /etc/localtime
    hwclock --systohc

    msg_ok "Timezone set to: $timezone"

    # --- Hostname ------------------------------------------------------------
    local hostname
    while true; do
        hostname=$(dialog_input "Hostname" \
            "Enter a hostname for this machine:" \
            "archlinux") || return 1

        # Validate: alphanumeric and hyphens, can't start/end with hyphen
        if [[ "$hostname" =~ ^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$ ]]; then
            break
        else
            dialog_msgbox "Invalid Hostname" \
                "Hostname must contain only letters, numbers, and hyphens,\nand cannot start or end with a hyphen."
        fi
    done

    echo "$hostname" > /etc/hostname
    write_env "HOSTNAME" "$hostname"

    # Create /etc/hosts — required for proper local hostname resolution.
    # Without this, sudo emits slow DNS warnings and some services misbehave.
    cat > /etc/hosts <<EOF
# Static table lookup for hostnames.
# See hosts(5) for details.

127.0.0.1   localhost
::1         localhost
127.0.1.1   ${hostname}
EOF

    msg_ok "Hostname set to: $hostname"

    dialog_msgbox "Timezone & Hostname" \
        "Timezone: ${timezone}\nHostname: ${hostname}"

    return 0
}
