set -o noclobber
NAME=tictac
LOCK=/tmp/$NAME.lock

error () {
  echo "$1" 1>&2
  exit 1
}

once () {
  if [ -f "$LOCK" ] 
  then     
    xterm -g 50x2 -e bash -c \
      "echo -n 'Daemon '$NAME' running pid='; cat $LOCK; sleep 5"
  fi
}

launch () {
  while true 
  do
    if sleep 60
    then once
    else exit 1
    fi
  done 
}

usage () {
    error "Usage: $0 [ -launch | -kill ] "
}

if [ $# != 1 ]
then
    usage
fi
case "$1" in
  -launch) 
     if [ -f "$LOCK" ]
     then
       error "Daemon already running (not launched)!"
     else
       echo -n '' > "$LOCK" || error "Cannot write $LOCK"
       echo -n "Launching $NAME... "
       launch &
       echo $! >> "$LOCK"
       echo "done (pid=$!)"
     fi
     ;;
  -kill)
     if [ -f "$LOCK" ]
     then
       PID=$(cat "$LOCK")
       case "$PID" in [1-9][0-9]*) ;; *) error "$LOCK does not contain a pid";; esac
       echo -n "Killing daemon $PID... "
       if kill -KILL "$PID"
       then
         echo "Done"
         rm "$LOCK"
       else
         echo "Process $PID not running (cleaning $LOCK)!" 1>&2
         rm "$LOCK"
         exit 1
       fi
     else
       error "Daemon not running"
     fi
     ;;
  *) usage
esac
