#!/bin/sh
# Instalace pluginu ÚZEI pro Codex.
#
# Served from the app itself at /install-plugin.sh, so the marketplace URL and
# the required Codex version come from the deployment rather than from a wiki
# page somebody forgets to update. Placeholders are substituted at serve time.
#
# Everything here is idempotent: running it twice is how someone upgrades.
set -eu

MARKETPLACE_URL="https://github.com/halymist/uzei-codex-plugin"
MIN_VERSION="0.147.0"
PLUGIN="uzei@uzei"
SERVER="uzei"

red() { printf '\033[31m%s\033[0m\n' "$1"; }
green() { printf '\033[32m%s\033[0m\n' "$1"; }
step() { printf '\n\033[1m%s\033[0m\n' "$1"; }

fail() {
  red "$1"
  exit 1
}

step "1/4  Kontrola Codexu"

if ! command -v codex >/dev/null 2>&1; then
  fail "Codex není nainstalovaný nebo není v PATH.
Nainstalujte aplikaci Codex, nebo příkazový řádek:
  npm install -g @openai/codex@latest"
fi

installed_version() {
  codex --version 2>/dev/null | tr ' ' '\n' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+' | head -1
}

version_at_least() {
  # Returns true when $1 >= $2. `sort -V` is the only version comparison we can
  # rely on in POSIX sh without pulling in a language runtime.
  [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" = "$2" ]
}

VERSION="$(installed_version || true)"
[ -n "$VERSION" ] || fail "Nepodařilo se zjistit verzi Codexu ('codex --version')."

if version_at_least "$VERSION" "$MIN_VERSION"; then
  green "Codex $VERSION vyhovuje (požadováno $MIN_VERSION nebo novější)."
else
  step "Codex $VERSION je starý, aktualizuji na $MIN_VERSION nebo novější"
  # Versions below the floor cannot complete the OAuth login at all: Codex
  # treats any request arriving on its loopback port as the authorization
  # response, so the browser's second request (a favicon fetch) aborts the
  # flow with "missing required issuer" even though the real callback
  # succeeded. Upgrading is the only fix; there is no workaround worth
  # documenting.
  if ! npm install -g @openai/codex@latest >/dev/null 2>&1; then
    # A global install into /usr/local fails without root. Codex installed in
    # the user's home was installed with a prefix, so retry with that one
    # rather than telling people to use sudo for a user-level tool.
    PREFIX="$(dirname "$(dirname "$(readlink -f "$(command -v codex)")")")"
    case "$PREFIX" in
      */lib/node_modules*) PREFIX="${PREFIX%%/lib/node_modules*}" ;;
    esac
    [ -n "$PREFIX" ] || PREFIX="$HOME/.local"
    npm install -g --prefix "$PREFIX" @openai/codex@latest >/dev/null 2>&1 ||
      fail "Aktualizace Codexu selhala. Zkuste ručně:
  npm install -g @openai/codex@latest"
  fi
  green "Codex aktualizován na $(installed_version)."
fi

step "2/4  Registrace zdroje pluginů"

# Adding a marketplace that is already registered is an error, not a no-op, so
# an upgrade path has to exist for the second run.
if codex plugin marketplace add "$MARKETPLACE_URL" >/dev/null 2>&1; then
  green "Zdroj přidán."
elif codex plugin marketplace upgrade "$SERVER" >/dev/null 2>&1; then
  green "Zdroj aktualizován."
else
  fail "Nepodařilo se přidat zdroj pluginů ($MARKETPLACE_URL)."
fi

step "3/4  Instalace pluginu"

codex plugin add "$PLUGIN" >/dev/null 2>&1 ||
  fail "Instalace pluginu selhala ('codex plugin add $PLUGIN')."
green "Plugin nainstalován."

step "4/4  Přihlášení k datům ÚZEI"

printf 'Otevře se prohlížeč. Přihlaste se účtem ÚZEI a potvrďte "Povolit".\n'

if ! codex mcp login "$SERVER"; then
  fail "Přihlášení selhalo. Zkuste znovu:
  codex mcp login $SERVER"
fi

# Trust the stored credential, not the exit code: the whole reason this script
# exists is that Codex has reported success while storing nothing.
if codex mcp list 2>/dev/null | grep -E "^$SERVER[[:space:]]" | grep -q "OAuth"; then
  printf '\n'
  green "Hotovo. Plugin ÚZEI je nainstalovaný a přihlášený."
  printf 'Restartujte aplikaci Codex, aby se plugin načetl.\n'
  printf 'Přístup můžete kdykoli odebrat: menu účtu → Připojené aplikace.\n'
else
  fail "Plugin je nainstalovaný, ale přihlášení se neuložilo.
Spusťte 'codex mcp login $SERVER' a ověřte, že 'codex mcp list'
ukazuje u řádku $SERVER hodnotu OAuth."
fi
