| 1 | #!/usr/bin/env bash |
| 2 | set -euo pipefail |
| 3 | |
| 4 | HOSTS_FILE="${HOSTS_FILE:-/etc/hosts}" |
| 5 | HOSTS=( |
| 6 | "grove.test" |
| 7 | "canopy.grove.test" |
| 8 | "ring.grove.test" |
| 9 | "collab.grove.test" |
| 10 | ) |
| 11 | |
| 12 | if [[ ! -f "$HOSTS_FILE" ]]; then |
| 13 | echo "Hosts file not found: $HOSTS_FILE" >&2 |
| 14 | exit 1 |
| 15 | fi |
| 16 | |
| 17 | missing=() |
| 18 | for host in "${HOSTS[@]}"; do |
| 19 | pattern="(^|[[:space:]])${host//./\\.}([[:space:]]|$)" |
| 20 | if ! grep -Eq "$pattern" "$HOSTS_FILE"; then |
| 21 | missing+=("$host") |
| 22 | fi |
| 23 | done |
| 24 | |
| 25 | if [[ ${#missing[@]} -eq 0 ]]; then |
| 26 | exit 0 |
| 27 | fi |
| 28 | |
| 29 | lines="" |
| 30 | for host in "${missing[@]}"; do |
| 31 | lines+="127.0.0.1 ${host}"$'\n' |
| 32 | done |
| 33 | |
| 34 | echo "Adding local host aliases to ${HOSTS_FILE}: ${missing[*]}" |
| 35 | |
| 36 | if [[ "$HOSTS_FILE" != "/etc/hosts" || -w "$HOSTS_FILE" ]]; then |
| 37 | printf "%s" "$lines" >> "$HOSTS_FILE" |
| 38 | exit 0 |
| 39 | fi |
| 40 | |
| 41 | if ! printf "%s" "$lines" | sudo tee -a /etc/hosts >/dev/null; then |
| 42 | echo "Failed to update /etc/hosts." >&2 |
| 43 | echo "Add these lines manually:" >&2 |
| 44 | printf "%s" "$lines" >&2 |
| 45 | exit 1 |
| 46 | fi |
| 47 | |