#!/bin/bash
# Regenerates /etc/issue on the installed system so the console tells the
# user which URL to open. Mirrors the live-ISO furtka-update-issue pattern:
# runs at boot and every few seconds from furtka-welcome.timer, so the IP
# fallback line is always on screen — with the address once DHCP handed one
# out, or with a "no IP yet" hint before that / after the cable is pulled.
# Only rewrites + nudges agetty when the text changed (no prompt flicker).
set -u

issue=/etc/issue

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

new=$(
    echo
    echo "  Furtka is ready."
    echo
    echo "  Open in a browser on another device on your network:"
    echo
    echo "      http://${hostname}.local   (easy — try this first)"
    if ((${#ips[@]})); then
        for ip in "${ips[@]}"; do
            echo "      http://${ip}   (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
)

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