#!/bin/sh
set -eu

staged="${1:-}"
[ -n "$staged" ] || exit 2
[ -f "$staged" ] || exit 2

hosts=/etc/hosts
[ -f "$hosts" ] || exit 2

tmp=$(mktemp /etc/.coldwork-hosts.XXXXXX)
trap 'rm -f "$tmp"' EXIT

awk '
function is_start(l) {
  return l == "# ColdWork-START" || l == "# ColdWork-STRICT-START" || l == "# ColdWork-PERMABAN-START" || l == "# ColdWork-RULES-START"
}
function is_end(l) {
  return l == "# ColdWork-END" || l == "# ColdWork-STRICT-END" || l == "# ColdWork-PERMABAN-END" || l == "# ColdWork-RULES-END"
}
{ line = $0; sub(/\r$/, "", line) }
FNR == NR {
  if (is_start(line)) { cut = 1; next }
  if (is_end(line)) { cut = 0; next }
  if (!cut) print line
  next
}
{
  if (is_start(line)) {
    if (inside) { bad = 1; exit 1 }
    inside = 1
    print line
    next
  }
  if (is_end(line)) {
    if (!inside) { bad = 1; exit 1 }
    inside = 0
    print line
    next
  }
  if (!inside) next
  if (line ~ /^(127\.0\.0\.1|::1)[ \t]+[a-z0-9][a-z0-9.-]*$/) { print line; next }
  bad = 1
  exit 1
}
END { if (bad || inside) exit 1 }
' "$hosts" "$staged" > "$tmp"

[ -s "$tmp" ] || exit 1

cat "$tmp" > "$hosts"
chmod 644 "$hosts"
resolvectl flush-caches >/dev/null 2>&1 || systemd-resolve --flush-caches >/dev/null 2>&1 || true
exit 0
