scripts/ensure-local-hosts.shblame
View source
a33b2b61#!/usr/bin/env bash
a33b2b62set -euo pipefail
a33b2b63
a33b2b64HOSTS_FILE="${HOSTS_FILE:-/etc/hosts}"
a33b2b65HOSTS=(
a33b2b66 "grove.test"
a33b2b67 "canopy.grove.test"
a33b2b68 "ring.grove.test"
bf6031c9 "collab.grove.test"
a33b2b610)
a33b2b611
a33b2b612if [[ ! -f "$HOSTS_FILE" ]]; then
a33b2b613 echo "Hosts file not found: $HOSTS_FILE" >&2
a33b2b614 exit 1
a33b2b615fi
a33b2b616
a33b2b617missing=()
a33b2b618for host in "${HOSTS[@]}"; do
a33b2b619 pattern="(^|[[:space:]])${host//./\\.}([[:space:]]|$)"
a33b2b620 if ! grep -Eq "$pattern" "$HOSTS_FILE"; then
a33b2b621 missing+=("$host")
a33b2b622 fi
a33b2b623done
a33b2b624
a33b2b625if [[ ${#missing[@]} -eq 0 ]]; then
a33b2b626 exit 0
a33b2b627fi
a33b2b628
a33b2b629lines=""
a33b2b630for host in "${missing[@]}"; do
a33b2b631 lines+="127.0.0.1 ${host}"$'\n'
a33b2b632done
a33b2b633
a33b2b634echo "Adding local host aliases to ${HOSTS_FILE}: ${missing[*]}"
a33b2b635
a33b2b636if [[ "$HOSTS_FILE" != "/etc/hosts" || -w "$HOSTS_FILE" ]]; then
a33b2b637 printf "%s" "$lines" >> "$HOSTS_FILE"
a33b2b638 exit 0
a33b2b639fi
a33b2b640
a33b2b641if ! printf "%s" "$lines" | sudo tee -a /etc/hosts >/dev/null; then
a33b2b642 echo "Failed to update /etc/hosts." >&2
a33b2b643 echo "Add these lines manually:" >&2
a33b2b644 printf "%s" "$lines" >&2
a33b2b645 exit 1
a33b2b646fi