#!/bin/bash

# omarchy:summary=Install Ghost and start it for this login
# omarchy:requires-sudo=true

set -euo pipefail

echo "Installing Ghost..."
omarchy-pkg-add ghost

# The package carries the daemon, the HUD plugin, the CLI, and the computer-use
# helper; browser automation uses the optional agent-browser CLI through Bash.
# Two things need this login's hand: the daemon is a user unit, and the HUD is
# an omarchy-shell plugin, so it is linked into this user's plugins directory
# and enabled in the shell already running.
echo "Starting Ghost for this login..."
systemctl --user daemon-reload
systemctl --user enable --now ghostd.service

mkdir -p ~/.config/omarchy/plugins
# -T, because plain `ln -sfn` onto an existing directory creates the link
# inside it and reports success, leaving a plugin the shell cannot load. A
# real directory there (an older install) is refused with the remedy instead.
plugin_link=~/.config/omarchy/plugins/ferdousbhai.ghost
if ! ln -sfnT /usr/share/ghost/plugin "$plugin_link" 2>/dev/null; then
  echo "$plugin_link is a real directory, probably from an older install." >&2
  echo "Move it aside and run this again:  mv $plugin_link{,.bak}" >&2
  exit 1
fi
omarchy-shell shell rescanPlugins
# Rescanning is asynchronous; wait for discovery before enabling the plugin.
discovered=0
for (( attempt = 0; attempt < 40; attempt++ )); do
  if omarchy-plugin-list --json | jq -e 'any(.[]; .id == "ferdousbhai.ghost")' >/dev/null; then
    discovered=1
    break
  fi
  sleep 0.05
done
if (( ! discovered )); then
  echo "The shell did not pick up the Ghost HUD plugin." >&2
  echo "Ghost is installed and running; enable the HUD with:  omarchy-plugin-enable ferdousbhai.ghost" >&2
  exit 1
fi
omarchy-plugin-enable ferdousbhai.ghost

echo ""
echo "Ghost is installed, and in your app launcher."
# The shell claims Super + Ctrl + G at runtime when no binding of the owner's
# holds it, and edits no configuration; a .conf Hyprland config, which runs
# no Lua, sources /usr/share/doc/ghost/shell-contrib/hyprland/ghost.conf.
echo "Summon it with Super + Ctrl + G."
echo ""
echo "Then make a ghost:  ghost new <name>   (its turns run on the agent CLIs you are signed into)"
