#!/bin/bash
# Privileged helper for Elon demon-mode /etc/hosts blocking.
# Installed once to /Library/PrivilegedHelperTools/com.elon.hosts-helper
set -euo pipefail

MARKER_START="# ELON_DEMON_BLOCK_START"
MARKER_END="# ELON_DEMON_BLOCK_END"
HOSTS="/etc/hosts"

flush_dns() {
    dscacheutil -flushcache >/dev/null 2>&1 || true
    killall -HUP mDNSResponder >/dev/null 2>&1 || true
}

remove_block() {
    if grep -q "$MARKER_START" "$HOSTS" 2>/dev/null; then
        sed -i '' "/${MARKER_START}/,/${MARKER_END}/d" "$HOSTS"
        flush_dns
    fi
}

cmd="${1:-}"
shift || true

case "$cmd" in
    enable)
        remove_block
        {
            echo ""
            echo "$MARKER_START"
            while IFS= read -r site || [[ -n "$site" ]]; do
                site="$(echo "$site" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
                [[ -z "$site" ]] && continue
                echo "127.0.0.1 $site"
            done
            echo "$MARKER_END"
            echo ""
        } >> "$HOSTS"
        flush_dns
        ;;
    disable)
        remove_block
        ;;
    status)
        if grep -q "$MARKER_START" "$HOSTS" 2>/dev/null; then
            exit 0
        fi
        exit 1
        ;;
    *)
        echo "Usage: $0 enable|disable|status" >&2
        exit 2
        ;;
esac
