#! /bin/sh
set -euf

if test "${nosudo-false}" != true -a `id -u` != 0; then
  echo "we're going sudo..." >&2
  exec sudo "$0" "$@"
  exit 23 # go to hell
fi

DIRNAME=`dirname $0`
export PATH="`readlink -f $DIRNAME`:$PATH"

hosts="${hosts-/etc/hosts}"

bs='# BEGIN OF RETIOLUM'
es='# END OF RETIOLUM'

case "${*-I am made of stupid}" in
  (start|restart)
    hosts | $0 replace magic
    ;;
  (stop)
    $0 clear magic
    ;;
  ('print magic')
    echo "$bs"
    cat
    echo "$es"
    ;;
  ('create magic')
    $0 has magic || $0 print magic >> $hosts < /dev/null
    ;;
  ('destroy magic')
    $0 has magic && sed -ie "/^$bs$/,/^$es$/d" $hosts 
    ;;
  ('has magic')
    grep -q "^$bs$" $hosts && grep -q "^$es$" $hosts
    ;;
  ('replace magic')
    $0 destroy magic && $0 print magic >> $hosts
    ;;
  ('clear magic')
    $0 replace magic < /dev/null
    ;;
  (*)
    echo 'Error 1: You are made of stupid!' >&2
    exit 23
esac