#!/bin/sh
set -eu

DOWNLOAD_URL="https://www.claudeusage.dev/downloads/claude-usage"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
LOCAL_SOURCE="$SCRIPT_DIR/claude-usage"
INSTALL_DIR=${CLAUDE_USAGE_INSTALL_DIR:-"$HOME/.local/bin"}
INSTALL_PATH="$INSTALL_DIR/claude-usage"
APPLICATIONS_DIR=${CLAUDE_USAGE_APPLICATIONS_DIR:-"$HOME/Applications"}
TARGET_APP="$APPLICATIONS_DIR/Claude Usage.app"
BUNDLE_ID="dev.claudeusage.menubar"
ACTION=${1:-install}

if [ "$#" -gt 2 ] || { [ "$#" -gt 1 ] && [ "$ACTION" != "--menu-bar" ]; } ||
    { [ "$ACTION" != "install" ] && [ "$ACTION" != "--uninstall" ] &&
      [ "$ACTION" != "--menu-bar" ] && [ "$ACTION" != "--uninstall-menu-bar" ]; }; then
    printf '%s\n' "Usage: claude-usage-install.sh [--uninstall | --menu-bar [APP_PATH] | --uninstall-menu-bar]" >&2
    exit 2
fi

app_identifier() {
    /usr/bin/plutil -extract CFBundleIdentifier raw -o - "$1/Contents/Info.plist" 2>/dev/null || true
}

quit_installed_app() {
    executable="$TARGET_APP/Contents/MacOS/ClaudeUsageMenuBar"
    if /usr/bin/pgrep -f -x "$executable" >/dev/null 2>&1; then
        /usr/bin/osascript -e 'tell application id "dev.claudeusage.menubar" to quit' >/dev/null 2>&1 || true
    fi
}

if [ "$ACTION" = "--uninstall-menu-bar" ]; then
    if [ ! -e "$TARGET_APP" ]; then
        printf '%s\n' "Claude Usage is not installed at $TARGET_APP"
        exit 0
    fi
    if [ -L "$TARGET_APP" ] || [ "$(app_identifier "$TARGET_APP")" != "$BUNDLE_ID" ]; then
        printf '%s\n' "Error: refusing to remove unexpected item at $TARGET_APP" >&2
        exit 1
    fi
    quit_installed_app
    "$TARGET_APP/Contents/MacOS/ClaudeUsageMenuBar" --unregister-login-item || {
        printf '%s\n' "Error: could not remove Claude Usage from login items; app was not removed." >&2
        exit 1
    }
    /bin/rm -R -- "$TARGET_APP"
    printf '%s\n' "Removed $TARGET_APP and its Launch at Login registration"
    printf '%s\n' "The claude-usage CLI was left installed. Remove it separately with --uninstall."
    exit 0
fi

if [ "$ACTION" = "--uninstall" ]; then
    if [ -e "$INSTALL_PATH" ]; then
        /bin/rm -f -- "$INSTALL_PATH"
        printf '%s\n' "Removed $INSTALL_PATH"
    else
        printf '%s\n' "claude-usage is not installed at $INSTALL_PATH"
    fi
    exit 0
fi

SOURCE_APP=""
if [ "$ACTION" = "--menu-bar" ]; then
    SOURCE_APP=${2:-"$SCRIPT_DIR/macos-menu-bar/release/Claude Usage.app"}
    if [ ! -d "$SOURCE_APP" ] || [ "$(app_identifier "$SOURCE_APP")" != "$BUNDLE_ID" ]; then
        printf '%s\n' "Error: Claude Usage.app not found or invalid at $SOURCE_APP" >&2
        printf '%s\n' "Use extracted beta app path, or run macos-menu-bar/build-release.sh first." >&2
        exit 1
    fi
fi

if ! command -v claude >/dev/null 2>&1; then
    printf '%s\n' "claude-usage installer: Claude Code is not installed or is not on PATH." >&2
    exit 1
fi
if ! command -v python3 >/dev/null 2>&1; then
    printf '%s\n' "claude-usage installer: Python 3.9 or newer is required." >&2
    exit 1
fi
if ! python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 9) else 1)'; then
    printf '%s\n' "claude-usage installer: Python 3.9 or newer is required." >&2
    exit 1
fi

/bin/mkdir -p -- "$INSTALL_DIR"
STAGED_CLI=$(mktemp "$INSTALL_DIR/.claude-usage-install.XXXXXX")
STAGING_APP=""
cleanup() {
    [ -z "${STAGED_CLI:-}" ] || /bin/rm -f -- "$STAGED_CLI"
    [ -z "${STAGING_APP:-}" ] || /bin/rm -R -- "$STAGING_APP"
}
trap cleanup EXIT HUP INT TERM

if [ -f "$LOCAL_SOURCE" ]; then
    /usr/bin/install -m 0755 "$LOCAL_SOURCE" "$STAGED_CLI"
else
    if ! command -v curl >/dev/null 2>&1; then
        printf '%s\n' "claude-usage installer: curl is required for a hosted install." >&2
        exit 1
    fi
    if ! curl -fsSL "$DOWNLOAD_URL" -o "$STAGED_CLI"; then
        printf '%s\n' "claude-usage installer: download failed; existing installation was preserved." >&2
        exit 1
    fi
    /bin/chmod 0755 "$STAGED_CLI"
fi

if ! "$STAGED_CLI" --version >/dev/null 2>&1; then
    printf '%s\n' "claude-usage installer: downloaded command failed validation." >&2
    exit 1
fi
/bin/mv -f -- "$STAGED_CLI" "$INSTALL_PATH"
STAGED_CLI=""
printf '%s\n' "Installed claude-usage to $INSTALL_PATH"

if [ "$ACTION" = "--menu-bar" ]; then
    if [ -e "$TARGET_APP" ] &&
       { [ -L "$TARGET_APP" ] || [ "$(app_identifier "$TARGET_APP")" != "$BUNDLE_ID" ]; }; then
        printf '%s\n' "Error: refusing to replace unexpected item at $TARGET_APP" >&2
        exit 1
    fi
    quit_installed_app
    /bin/mkdir -p -- "$APPLICATIONS_DIR"
    STAGING_APP=$(mktemp -d "$APPLICATIONS_DIR/.claude-usage-install.XXXXXX")
    /usr/bin/ditto "$SOURCE_APP" "$STAGING_APP/Claude Usage.app"
    if [ "$(app_identifier "$STAGING_APP/Claude Usage.app")" != "$BUNDLE_ID" ]; then
        printf '%s\n' "Error: copied application failed validation." >&2
        exit 1
    fi
    if [ -e "$TARGET_APP" ]; then
        /bin/rm -R -- "$TARGET_APP"
    fi
    /bin/mv -- "$STAGING_APP/Claude Usage.app" "$TARGET_APP"
    /bin/rmdir "$STAGING_APP"
    STAGING_APP=""
    printf '%s\n' "Installed Claude Usage.app to $TARGET_APP"
    printf '%s\n' "Unsigned beta: macOS may require Open Anyway in System Settings > Privacy & Security."
    /usr/bin/open "$TARGET_APP" || true
fi

trap - EXIT HUP INT TERM
case ":${PATH:-}:" in
    *":$INSTALL_DIR:"*) printf '%s\n' "Run: claude-usage" ;;
    *) printf '%s\n' "Add $INSTALL_DIR to PATH, then run: claude-usage" ;;
esac
printf '%s\n' "Uninstall: $0 --uninstall"
