#!/usr/bin/env nix-shell
#!nix-shell -i bash -p inotify-tools waybar mako swaynotificationcenter libnotify pavucontrol

# This script will watch waybar.nix and compile it to /tmp/waybar.json.  Offers
# a much tighter feedback loop than that offered by the Nix module.

# Inotify will sometimes double-fire events.  We avoid unnecessary recompilation
# by putting a cooldown on builds.
last_build=0
waybar_pid=""

update () {
  last_build="$(date +%s)"

  if [ ! -z "$waybar_pid" ]; then
      kill "$waybar_pid"
      echo >&2 "Killed waybar..."
      waybar_pid=""
  fi

  echo >&2 "Building waybar.json..."
  nix eval --impure --json --expr "import ./waybar.nix {}" \
      > /tmp/waybar.json \
      && echo >&2 "Built waybar.json!"
  waybar -c waybar.json -b sydbar -s waybar.css 2>&1 >/dev/null &
  waybar_pid=$!
  echo >&2 "Started Waybar [$waybar_pid]" 
}

update

inotifywait -me modify waybar.nix waybar.css cycle_notifications.clj |
    while read _ _ file_name; do
        ct="$(date +%s)"
        if (( ct - last_build < 1 )); then
            echo >&2 "Ignoring event (on cooldown)"
        else
            update
        fi
    done
