#!/bin/bash

# omarchy:summary=Set up Omarchy's extensions and defaults for Pi
# omarchy:args=[omarchy-root]
# omarchy:hidden=true

# Pi gets Omarchy's package of extensions (web_fetch, web_search, and the Omarchy look),
# which it discovers as a folder in its extensions directory,
# linked from one Omarchy tree: the package, or the checkout `omarchy dev link`
# points at. A link into another Omarchy tree is moved to this one, and a
# folder or a link of the user's own by that name wins. Settings are only
# written where the user hasn't chosen.

set -euo pipefail

root=${1:-$OMARCHY_PATH}
pi_dir=~/.pi/agent
mkdir -p "$pi_dir"

package="$root/default/agents/pi"
link="$pi_dir/extensions/omarchy"
if [[ -L $link && $(readlink "$link") == */default/agents/pi ]]; then
  rm "$link"
fi
if [[ -d $package && ! -e $link && ! -L $link ]]; then
  mkdir -p "${link%/*}"
  ln -s "$package" "$link"
fi

# Pi shows its whole changelog after every update, and Omarchy keeps Pi
# updated, so it is condensed to one line. Startup goes straight to the
# editor, without Pi's header or the listing of loaded context, skills and
# extensions. A setting the user has chosen stays, and a settings
# file linked from the user's dotfiles is written through the link.
defaults='{"collapseChangelog": true, "quietStartup": true}'
settings="$pi_dir/settings.json"
if [[ ! -e $settings && ! -L $settings ]]; then
  jq -n "$defaults" >"$settings"
elif jq -e --argjson defaults "$defaults" 'type == "object" and ($defaults | keys) - keys != []' "$settings" &>/dev/null; then
  target=$(realpath "$settings")
  tmp=$(mktemp "$target.XXXXXX")
  jq --argjson defaults "$defaults" '$defaults + .' "$target" >"$tmp" && mv "$tmp" "$target"
fi
