#!/usr/bin/env bash
# Point the stable hostname `flm-host` at the Windows host.
#
# WSL2 (NAT mode) assigns a new gateway address on every start, so the Windows
# host IP is not stable. Configs reference `flm-host` instead of an IP; this
# script rewrites that entry in /etc/hosts at each WSL boot.
#
# Wired up via /etc/wsl.conf:  [boot] command = /usr/local/bin/update-flm-host.sh
# Safe to run by hand at any time (idempotent).
set -euo pipefail

HOSTS_FILE=/etc/hosts
ALIAS=flm-host

ip=$(ip route show default | awk '/default/ {print $3; exit}')
if [ -z "${ip}" ]; then
    echo "update-flm-host: no default route, leaving ${HOSTS_FILE} untouched" >&2
    exit 1
fi

# Drop any previous entry, then append the current one. Rewriting in place
# (rather than mv) keeps WSL's bind-mounted /etc/hosts happy.
tmp=$(mktemp)
grep -v "[[:space:]]${ALIAS}\([[:space:]]\|$\)" "${HOSTS_FILE}" > "${tmp}" || true
printf '%s\t%s\n' "${ip}" "${ALIAS}" >> "${tmp}"
cat "${tmp}" > "${HOSTS_FILE}"
rm -f "${tmp}"

echo "update-flm-host: ${ALIAS} -> ${ip}"
