#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash -p s6 -p s6-rc

# for default $PATH to take precedence over nix-shell PATH if invoked interactively,
# otherwise we invoke a s6-rc which does not know where to find files.
export PATH="/etc/profiles/per-user/$(whoami)/bin:/run/current-system/sw/bin:$PATH"

usage() {
  echo "swaync-service-dispatcher <action> <service>"
  echo ""
  echo "actions:"
  echo "- print <service>"
  echo "  prints 'true' or 'false' based on if the service is wanted-up (i.e. started or starting)"
  echo "- up <service>"
  echo "- down <service>"
  echo "- toggle <service>"
  exit 1
}

action="$1"
service="$2"

log() {
  if [ -n "$SWAYNC_DEBUG" ]; then
    printf "%s\n" "$1"
  fi
}

checkActive() {
  # simulate a dry-run start. if no actions would be performed, then the service is up.
  # alternative is s6-svstat, but that doesn't support oneshots
  local s6Output=$(s6-rc -n 0 -b start "$service")
  if [ -z "$s6Output" ]; then
    echo true
  else
    echo false
  fi
}
startService() {
  log "startService: $service"
  s6-rc -b start "$service"
}
stopService() {
  log "stopService: $service"
  s6-rc -b stop "$service"
}

case "$action" in
  (print)
    checkActive
    ;;
  (toggle)
    case "$(checkActive)" in
      false)
        startService
        ;;
      true)
        stopService
        ;;
    esac
    ;;
  # these aren't needed by swaync; just handy because i can never remember how to use s6
  (up)
    startService
    ;;
  (down)
    stopService
    ;;
  (*)
    usage
    ;;
esac
