#!/bin/bash

# omarchy:summary=Update mise-managed tools

if omarchy-cmd-present mise; then
  echo -e "\e[32m\nUpdate mise tools\e[0m"

  # mise withholds releases younger than its cooldown, so tools stay behind for
  # days after they ship. Running omarchy update is the user asking for current
  # versions now, which is the same call the mup alias makes by hand.
  MISE_MINIMUM_RELEASE_AGE=0 mise up

  # Grok's npm launcher runs ~/.grok/bin/grok whenever it exists, and the
  # package's install script that points it at a new release doesn't run
  # under mise, so updates never took effect. Dropping a link to an older
  # release lets the launcher unpack the installed one, which --version does
  # now rather than on the next session. The old release stays until the new
  # one is in place, and comes back if it never arrives.
  if grok_dir=$(mise where npm:@xai-official/grok 2>/dev/null) && [[ -n $grok_dir ]]; then
    grok_link="$HOME/.grok/bin/grok"
    grok_current="grok-${grok_dir##*/}"
    grok_previous=$(readlink "$grok_link" 2>/dev/null)
    if [[ -L $grok_link && $grok_previous != "$grok_current" ]]; then
      rm -f "$grok_link"
      mise x npm:@xai-official/grok -- grok --version >/dev/null 2>&1
      if [[ $(readlink "$grok_link" 2>/dev/null) == "$grok_current" ]]; then
        find "$HOME/.grok/bin" -maxdepth 1 -name 'grok-*' ! -name "$grok_current" -delete
      else
        ln -sfn "$grok_previous" "$grok_link"
      fi
    fi
  fi
fi
