#!/usr/bin/env bash
# Keep 127.0.1.1 in /etc/hosts in sync with the active hostname
set -u
HN="$(hostname 2>/dev/null || true)"
[ -n "$HN" ] || exit 0
[ -w /etc/hosts ] || exit 0
if grep -qE '^127\.0\.1\.1[[:space:]]' /etc/hosts; then
  sed -i -E "s|^127\.0\.1\.1[[:space:]].*|127.0.1.1\t${HN}|" /etc/hosts || true
else
  printf "127.0.1.1\t%s\n" "$HN" >> /etc/hosts || true
fi
exit 0
