#!/bin/bash
#
# monitor /var/log/syslog for the latest pygopherd item and do stuff if it is a request for /toggle
#
# Uses $ usbrelay
# WHich came from here: https://github.com/darrylb123/usbrelay
#
# Started from Command Line Using $ sudo nohup /var/gopher/bin/.toggle.sh &
# By Tim at TildeCow

# "lamp" inits to "OFF" state
position="OFF"

while true # Remember kids, NEVER, NEVER, E-V-E-R use infinite loops!
do
# Scan syslog for new entry indicating call to toggle gophermap
entry=$(zgrep pygopherd /var/log/syslog | tail -n 1)
if [[ $entry == *"/toggle"* ]]; then
  # If lamp is OFF, turn lamp ON
  if [[ $position == "OFF" ]]; then
     position="ON"
     # Update wording
     sed -i 's/OFF]/ON]/g' /var/gopher/gophermap
     sed -i 's/ON]/OFF]/g' /var/gopher/toggle/gophermap
     # Actually energize relay!
     usbrelay BITFT_1=1 2>/dev/null
  # If lamp is ON, turn it OFF
  elif [[ $position == "ON" ]]; then
     position="OFF"
     # Update wording
     sed -i 's/ON]/OFF]/g' /var/gopher/gophermap
     sed -i 's/OFF]/ON]/g' /var/gopher/toggle/gophermap
     # Actually de-energize relay
     usbrelay BITFT_1=0 2>/dev/null
  fi
  # Note our action in syslog
  logger pygopherd toggled!
fi

done