#!/usr/bin/env bash
set -euo pipefail

MODE="${1:-add}"
HOSTS_FILE="/etc/hosts"
BEGIN_MARK="# >>> androidcast-local >>>"
END_MARK="# <<< androidcast-local <<<"

BLOCK=$(cat <<'EOF'
# >>> androidcast-local >>>
127.0.0.1 apps.androidcast.local
127.0.0.1 git.androidcast.local
127.0.0.1 crashes.androidcast.local
# <<< androidcast-local <<<
EOF
)

if [[ "$MODE" == "remove" ]]; then
  sudo awk -v begin="$BEGIN_MARK" -v end="$END_MARK" '
    $0==begin {skip=1; next}
    $0==end {skip=0; next}
    !skip {print}
  ' "$HOSTS_FILE" | sudo tee "$HOSTS_FILE" >/dev/null
  echo "Removed androidcast-local hosts entries."
  exit 0
fi

if grep -Fq "$BEGIN_MARK" "$HOSTS_FILE"; then
  echo "Entries already exist in $HOSTS_FILE"
  exit 0
fi

printf "\n%s\n" "$BLOCK" | sudo tee -a "$HOSTS_FILE" >/dev/null
echo "Added androidcast-local hosts entries."
