#!/usr/bin/env bash

## Run a command as a background process or kill all instances of the command if
## any are running.
##
## Usage: toggle <command> [<command-arg>...]
##
## Dependencies: GNU sed, procps
##
## I use this script to play and stop my favorite white noise audio file
## <https://boxfansound.com/> via a window manager key binding.

set -euo pipefail
shopt -s inherit_errexit

die() { echo "${0##*/}: $1" >&2; exit 1; }

[[ " $* " =~ ' --help ' ]] && sed -n 's/^## \?//p' "$0" && exit
(( $# )) || die 'missing argument'

cmd=$1
type "$cmd" &> /dev/null || die "command not found: $cmd"
pkill "${cmd::15}" || ("$@" &> /dev/null &)
