#!/bin/bash

# omarchy:summary=Give each local model that is set up a launcher of its own, and take away those of models removed
# omarchy:hidden=true

# A model set up on this machine gets a launcher beside Agent, as signing in to
# Claude, Codex or Grok adds one: its name, its vendor's logo, and an agent
# opened on it, in the default agent where that can take a local model and in
# pi or OpenCode where it can't. Removing the model takes the launcher away.
# An image, video or music model gets none: no agent runs on one, and Fantasi
# lists them itself.
#
# This makes the launchers match the models set up right now, so it is safe to
# run at any time: omarchy-models runs it after a setup or a removal, and
# the shell when a setup the agents panel started in the background has finished.

APPLICATIONS="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
ICONS="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/scalable/apps"
LOGOS="$OMARCHY_PATH/shell/plugins/agents/assets"
PREFIX="omarchy-models-"
STATE="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agent-local"
FALLBACK_ICONS="$STATE/icons"
CURRENT="$HOME/.local/state/omarchy/current"
CURRENT_ICONS="$CURRENT/icons"

shopt -s nullglob

is_theme_icon_link() {
  [[ -L $1 && -e $1 && $(readlink "$1") == "$CURRENT_ICONS/"* ]]
}

# The vendor's logo on a dark tile, which reads under any theme: most of the
# logos are white, drawn for the dark agents panel. The logo's own <svg> turns
# into a group scaled to the tile, keeping the fill its root may carry.
draw_icon() {
  local vendor=$1 target=$2 logo svg attrs body x y w h transform
  logo="$LOGOS/$vendor.svg"
  [[ -f $logo ]] || logo="$LOGOS/local.svg"

  svg=$(tr '\n' ' ' <"$logo")
  [[ $svg =~ \<svg([^\>]*)\>(.*)\</svg\> ]] || return 1
  attrs=${BASH_REMATCH[1]}
  body=${BASH_REMATCH[2]}
  [[ $attrs =~ viewBox=\"([^\"]*)\" ]] || return 1
  read -r x y w h <<<"${BASH_REMATCH[1]//,/ }"
  transform=$(awk -v x="$x" -v y="$y" -v w="$w" -v h="$h" 'BEGIN {
    scale = 272 / (w > h ? w : h)
    printf "translate(%.3f %.3f) scale(%.5f)", 256 - (x + w / 2) * scale, 256 - (y + h / 2) * scale, scale
  }')
  attrs=$(sed -E 's/ (xmlns|viewBox|width|height|style)="[^"]*"//g' <<<"$attrs")

  cat >"$target.tmp" <<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
  <rect x="32" y="32" width="448" height="448" rx="104" fill="#16161e" stroke="#3b3d52" stroke-width="8"/>
  <g transform="$transform"$attrs>$body</g>
</svg>
SVG
  mv -f "$target.tmp" "$target"
}

mkdir -p "$APPLICATIONS" "$ICONS" "$STATE" "$FALLBACK_ICONS" "$CURRENT"

# omarchy-models and the shell can both run this after the same
# setup or removal. Each removes what isn't in its own reading of the models,
# so one at a time, from that reading to the last file removed.
exec 9>"$STATE/launchers.lock"
flock 9

# A reading that fails says nothing about which models are gone, so the
# launchers stay as they are rather than all being taken away. Models still
# downloading, or on their way out, have nothing to open yet.
if ! status=$(omarchy-models status --json 2>/dev/null) ||
  ! jq -e '.models | type == "object"' <<<"$status" >/dev/null 2>&1; then
  echo "Couldn't read which local models are set up" >&2
  exit 1
fi
mapfile -t models < <(jq -r '
  .models | to_entries[]
  | select(.value.unit != "installing" and .value.unit != "removing")
  | select((.value.kind // "text") == "text")
  | [.key, (.value.name // .key | gsub("[[:cntrl:]]"; " ")), (.value.vendor // "local")] | @tsv' <<<"$status")

# Share .icons.lock with omarchy-theme-set-icons while checking, linking, and
# pruning hicolor icon links so a concurrent icon-set switch cannot race.
exec 7>"$CURRENT/.icons.lock"
flock 7

declare -A entries=() icons=()

for model in "${models[@]}"; do
  IFS=$'\t' read -r recipe name vendor <<<"$model"
  # The recipe goes on a command line and the vendor into a file name.
  [[ $recipe =~ ^[a-z0-9][a-z0-9._-]*$ ]] || continue
  [[ $vendor =~ ^[a-z0-9-]+$ ]] || vendor="local"
  [[ -n $name ]] || name=$recipe

  entry="$PREFIX$recipe.desktop"
  icon="$PREFIX$vendor"
  app_id="org.omarchy.local.$recipe"
  entries[$entry]=1

  if [[ -z ${icons[$icon.svg]:-} ]]; then
    if draw_icon "$vendor" "$FALLBACK_ICONS/$icon.svg"; then
      # Keep the active icon set's themed icon when one is linked; otherwise
      # link the generated fallback tile (used under Original and for vendors
      # a set does not draw).
      if ! is_theme_icon_link "$ICONS/$icon.svg"; then
        ln -sfn "$FALLBACK_ICONS/$icon.svg" "$ICONS/$icon.svg"
      fi
      icons[$icon.svg]=1
    elif ! is_theme_icon_link "$ICONS/$icon.svg"; then
      icon="omarchy-agent"
    fi
  fi

  cat >"$APPLICATIONS/$entry.tmp" <<ENTRY
[Desktop Entry]
Version=1.0
Name=$name
Comment=Start a coding agent on $name, running on this machine
Exec=omarchy-agent --local-model $recipe --app-id=$app_id
Icon=$icon
X-Omarchy-Titlebar-Icon=$icon-logo
StartupWMClass=$app_id
Terminal=false
Type=Application
Categories=Development;
X-Omarchy-Dock-Click=new
ENTRY
  chmod 644 "$APPLICATIONS/$entry.tmp"
  mv -f "$APPLICATIONS/$entry.tmp" "$APPLICATIONS/$entry"
done

# What a model removed since the last run left behind.
for entry in "$APPLICATIONS/$PREFIX"*.desktop; do
  [[ -n ${entries[${entry##*/}]:-} ]] || rm -f "$entry"
done
for icon in "$FALLBACK_ICONS/$PREFIX"*.svg; do
  [[ -n ${icons[${icon##*/}]:-} ]] || rm -f "$icon"
done
for icon in "$ICONS/$PREFIX"*.svg; do
  is_theme_icon_link "$icon" && continue
  [[ -n ${icons[${icon##*/}]:-} ]] || rm -f "$icon"
done

update-desktop-database "$APPLICATIONS" 2>/dev/null || true
