#!/bin/sh
# Runs as ROOT during pkg install. Register with Claude Desktop in the context of
# the logged-in user so it writes to ~/Library/Application Support/Claude.
set -e

INSTALL_DIR="/Library/Application Support/SerialConsoleMCP"
BIN="$INSTALL_DIR/serial-console-mcp"

CONSOLE_USER=$(stat -f "%Su" /dev/console 2>/dev/null || echo "")
if [ -z "$CONSOLE_USER" ] || [ "$CONSOLE_USER" = "root" ]; then
  # No logged-in GUI user we can target; let the install finish anyway.
  exit 0
fi

USER_UID=$(id -u "$CONSOLE_USER")
USER_HOME=$(dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory 2>/dev/null | sed 's/^NFSHomeDirectory: //')

launchctl asuser "$USER_UID" sudo -u "$CONSOLE_USER" \
  "$BIN" configure --command "$BIN" --config-home "$USER_HOME" || true

exit 0
