#!/bin/sh
# repoman :: claude-share launcher
# (C)opyright 2026, Leafscale, LLC - https://www.leafscale.com
# License: <see LICENSE file included with the repoman source>
#
# Bind-mounted read-only into containers at ${HOME}/.local/bin/claude by the
# claude-share profile. The host's ${HOME}/.local/share/claude/versions/ tree
# is mounted read-only alongside it; this launcher always execs the HIGHEST
# version present, so a host-side `claude update` propagates to already-running
# containers with no restart.
#
# Self-update from inside a container is intercepted: the install is shared and
# read-only, so upgrades must happen on the host (every container inherits it).

set -eu

# Resolve our own path even when invoked as a bare name via $PATH, then derive
# the install prefix from it. We can't use $HOME: the mount lands at the *host*
# user's home path, which need not match the container user's $HOME.
prog="$0"
case "$prog" in
    */*) ;;
    *)   prog="$(command -v -- "$prog" 2>/dev/null || printf '%s' "$prog")" ;;
esac
self="$(readlink -f -- "$prog" 2>/dev/null || printf '%s' "$prog")"
bindir="$(dirname -- "$self")"          # <prefix>/.local/bin
localdir="$(dirname -- "$bindir")"      # <prefix>/.local
versions="$localdir/share/claude/versions"

# Intercept the self-updater: the shared binary tree is read-only.
case "${1:-}" in
    update|upgrade|--upgrade)
        printf '%s\n' "claude is shared read-only from the host by repoman (claude-share)." >&2
        printf '%s\n' "Upgrade on the host with 'claude update'; containers pick it up on next launch." >&2
        exit 1
        ;;
esac

# Pick the highest semver-named version under the shared versions/ directory.
latest="$(ls -1 "$versions" 2>/dev/null | grep -E '^[0-9]+(\.[0-9]+)+$' | sort -V | tail -n1)"
if [ -z "$latest" ]; then
    printf '%s\n' "claude: no shared versions found under $versions" >&2
    printf '%s\n' "claude: is the claude-share profile attached and the container started?" >&2
    exit 127
fi

exec "$versions/$latest" "$@"
