#!/bin/bash

# omarchy:summary=Pick a shell plugin to enable, disable, clone, or remove
# omarchy:group=menu
# omarchy:name=plugin
# omarchy:args=<enable|disable|clone|remove>

set -euo pipefail

PLUGIN_ICON=$'\U000f0431'

case "${1:-}" in
  enable) filter='(.enabled | not)' ;;
  disable) filter='.canDisable and .enabled' ;;
  clone) filter='.firstParty and (.id as $id | ($plugins | map(.clonedFrom // "") | index($id)) == null)' ;;
  remove) filter='(.firstParty | not)' ;;
  *)
    echo "Usage: omarchy-menu-plugin <enable|disable|clone|remove>" >&2
    exit 1
    ;;
esac

# Whole sentences per verb, so a translation can inflect the verb.
case $1 in
  enable) title=$(omarchy-i18n plugin.enableTitle) none=$(omarchy-i18n plugin.noneToEnable) ;;
  disable) title=$(omarchy-i18n plugin.disableTitle) none=$(omarchy-i18n plugin.noneToDisable) ;;
  clone) title=$(omarchy-i18n plugin.cloneTitle) none=$(omarchy-i18n plugin.noneToClone) ;;
  remove) title=$(omarchy-i18n plugin.removeTitle) none=$(omarchy-i18n plugin.noneToRemove) ;;
esac

plugins=$(omarchy-plugin-list --json)

# The id rides along as row subtext: it tells same-named plugins apart on
# screen and comes back with the selection as the key to act on.
rows=$(jq -r --arg icon "$PLUGIN_ICON" \
  ". as \$plugins
   | .[] | select($filter)
   | \$icon + \"\\t\" + .name + \"\\t\" + .id" <<<"$plugins")
[[ -n $rows ]] || { omarchy-notification-send "$none"; exit 0; }

selection=$(omarchy-menu-select "$title" <<<"$rows") || exit 0
[[ -n $selection ]] || exit 0

id=$(cut -f2 <<<"$selection")
[[ -n $id ]] || exit 1

if [[ $1 == "clone" ]]; then
  omarchy-launch-floating-terminal-with-presentation \
    "omarchy-plugin-clone $(printf '%q' "$id") --edit"
elif [[ $1 == "remove" ]]; then
  omarchy-launch-floating-terminal-with-presentation "omarchy-plugin-remove $(printf '%q' "$id")"
else
  "omarchy-plugin-$1" "$id"
fi
