#!/usr/bin/env bash

# omarchy:summary=Install Cattle Drover, the agent harness manager, from its git checkout
# omarchy:requires-sudo=true

# Based: a git clone into DROVER_DIR and its own make install: the full
# launchd and tmux setup on a Mac, the deps, build and links targets on
# Linux, where make install would pretend launchd exists. A config repo in
# DROVER_CONFIG is attached with drover init; an existing one is applied.

set -eo pipefail

drover_dir=${DROVER_DIR:-$HOME/Projects/bitspur/cattle-drover}
drover_git=${DROVER_GIT:-https://github.com/clayrisser/cattle-drover.git}
drover_bin="$HOME/.local/bin/drover"

echo "Installing Cattle Drover..."
omarchy-pkg-add git make linux=only

if [[ -e $drover_dir && ! -d $drover_dir/.git ]]; then
  echo "$drover_dir exists but is not a git checkout" >&2
  exit 1
fi
if [[ ! -d $drover_dir/.git ]]; then
  mkdir -p "$(dirname "$drover_dir")"
  git clone "$drover_git" "$drover_dir"
fi

if [[ ! -x $drover_bin ]]; then
  case $(omarchy-os) in
  darwin) make -C "$drover_dir" install ;;
  *) make -C "$drover_dir" install/deps install/build install/links ;;
  esac
fi

if [[ ! -x $drover_bin ]]; then
  echo "$drover_bin is missing; the install did not produce it" >&2
  exit 1
fi

if [[ -d $HOME/.config/drover/.git ]]; then
  "$drover_bin" apply
elif [[ -n ${DROVER_CONFIG:-} ]]; then
  "$drover_bin" init "$DROVER_CONFIG"
else
  echo "Attach a config repository with: drover init <git url>"
fi
