#!/usr/bin/env bash

# omarchy:summary=Run the GNU build of a tool on whatever OS this is
# omarchy:args=<tool> [args...]
# omarchy:hidden=true

# The scripts lean on GNU flags: sed's -i, base64's -w 0, flock. Debian's
# tools are GNU. macOS ships BSD sed and base64 and no flock at all, and brew
# installs the GNU ones beside them under g-prefixed names (gsed from gnu-sed,
# gbase64 from coreutils) and flock from its own formula. A caller puts
# omarchy-gnu in front of the tool and the OS check lives here, nowhere else.

tool=$1
shift || true

if [[ -z $tool ]]; then
  echo "Usage: omarchy-gnu <tool> [args...]" >&2
  exit 2
fi

if [[ $(uname -s) != Darwin ]]; then
  exec "$tool" "$@"
fi

case $tool in
flock) gnu=flock formula=flock ;;
sed) gnu=gsed formula=gnu-sed ;;
find | xargs) gnu="g$tool" formula=findutils ;;
grep) gnu=ggrep formula=grep ;;
*) gnu="g$tool" formula=coreutils ;;
esac

if command -v "$gnu" >/dev/null 2>&1; then
  exec "$gnu" "$@"
fi

echo "omarchy-gnu: $gnu is not installed, so $tool cannot run: brew install $formula" >&2
exit 127
