DWM_DIR="$HOME/.dwm"
DWM_LOG="$DWM_DIR/stdout.log"
DWM_ERR="$DWM_DIR/stderr.log"
DWM_FIFO="$DWM_DIR/display_status.fifo"
STATUS_SCRIPT="$DWM_DIR/dwm_status.lua"

###########################################################################
echo 'Saving old logfiles.'
mv -f "$DWM_LOG" "$DWM_LOG.old.log"
mv -f "$DWM_ERR" "$DWM_ERR.old.log"

echo 'Resetting logfiles.'
date >|"$DWM_LOG"
date >|"$DWM_ERR"

echo "Redirecting to logfiles:"
echo '   stdout >> '$DWM_LOG
echo '   stderr >> '$DWM_ERR
exec >>"$DWM_LOG" 2>>"$DWM_ERR"

###########################################################################
## special handling for starts vs restarts
#
RESTART_FLAG="RESTART"
if [ "$1" = "$RESTART_FLAG" ]; then
   echo "Restarting $0"
else
   echo "Starting $0"
   # this is a clean start - do the things that should only be done once   

   echo 'Setting desktop colour'
   # rgb:20/0/20 = a dark purple
   xsetroot -solid rgb:20/0/20 

   if [ -r ~/.Xresources ]; then
      echo 'Merging .XResources'
      xrdb -merge ~/.Xresources
   fi

   #if [ -r ~/.fonts/ ]; then
   #   echo 'Adding ~/.fonts to font path'
   #   xset fp+ ~/.fonts/
   #fi

   if [ -r ~/.xmodmap ]; then
      echo 'Updating keyboard from .xmodmap'
      xmodmap ~/.xmodmap
   fi

   # don't start xautolock if this is 'L28' - it crashes on this machine
   [ "$HOST" = "L28" ] || if [ -x /usr/bin/xautolock ]; then
      echo 'Starting xautolock.'
      /usr/bin/xautolock &
   fi
fi

###########################################################################
echo 'Setting keyboard rate.'
xset r rate 350 40

###########################################################################
echo 'Starting dwm_status.'
[ -e "$DWM_FIFO" ] || mkfifo "$DWM_FIFO"
[ -p "$DWM_FIFO" ] && lua "$STATUS_SCRIPT" >"$DWM_FIFO" &
STATUS_SCRIPT_PID=$!

###########################################################################
echo "Starting dwm."
echo =============
#echo "Starting dwm with redirected outputs:"
#echo "   stdout > $DWM_LOG"
#echo "   stderr > $DWM_ERR"

# Was previously using exec dwm, but that didn't allow for the restart stuff
# It did have the advantage of closing the current shell & therefore saving memory
#dwm <"$DWM_FIFO" >>"$DWM_LOG" 2>>"$DWM_ERR"
dwm <"$DWM_FIFO"

###########################################################################
echo 'Killing dwm_status.'
kill $STATUS_SCRIPT_PID

###########################################################################
echo 'Asking about restart.'
# need to use /bin/echo to guarantee -e support (which is not a valid cmdline option in dash builtin echo)
/bin/echo -en "y\nn" | dmenu -p "Restart DWM?" | grep -q 'y' && exec $0 $RESTART_FLAG

echo "$0 terminating."
