#!/bin/bash
# Regenerates /etc/issue so the live-ISO console tells the user which URL
# to open in their browser. Shows proksi.local (via avahi/mDNS) as the
# preferred URL and the raw IP as a fallback for networks where mDNS
# doesn't work.
#
# Runs at boot and then every few seconds from furtka-issue.timer, so the
# fallback line is *always* on screen: with the address once DHCP has
# handed one out, or with a "no IP yet" hint before that / when the cable
# is unplugged. Only rewrites + nudges agetty when the text actually
# changed, so the login prompt doesn't flicker on every tick.
set -u

issue=/etc/issue

mapfile -t ips < <(ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1)

new=$(
    echo
    echo "  Open Furtka in a browser on another device on your network:"
    echo
    echo "      http://proksi.local:5000   (easy — try this first)"
    if ((${#ips[@]})); then
        for ip in "${ips[@]}"; do
            echo "      http://${ip}:5000   (fallback if the first doesn't work)"
        done
    else
        echo "      (fallback: no IP address yet — waiting for the network."
        echo "       Check the cable / DHCP. This line updates by itself.)"
    fi
    echo
    echo "  Then follow the wizard to install Furtka on this machine."
    echo
    echo "  Need a shell? Log in as root (no password)."
    echo
)

if [ "$new" != "$(cat "$issue" 2>/dev/null)" ]; then
    printf '%s\n' "$new" > "$issue"
    agetty --reload 2>/dev/null || true
fi
