#!/usr/bin/env sh
# Install IuVe Connect Agent.app into ~/Applications and optional LaunchAgent for headless run.
# Usage: install_console_app.sh [agent_root]
set -eu

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
DEFAULT_ROOT="/opt/iuve-connect-desktop-agent"
AGENT_ROOT="${1:-}"
if [ -z "$AGENT_ROOT" ]; then
  if [ -d "$DEFAULT_ROOT/iuve_connect_agents" ]; then
    AGENT_ROOT="$DEFAULT_ROOT"
  else
    # Repo / staged tree: adapters/macos → ../../../../.. = agent package root when staged
    CANDIDATE="$(CDPATH= cd -- "$SCRIPT_DIR/../../../.." && pwd)"
    if [ -d "$CANDIDATE/iuve_connect_agents" ]; then
      AGENT_ROOT="$CANDIDATE"
    else
      AGENT_ROOT="$DEFAULT_ROOT"
    fi
  fi
fi

SRC_APP="$SCRIPT_DIR/IuVe Connect Agent.app"
if [ ! -d "$SRC_APP" ]; then
  SRC_APP="$AGENT_ROOT/iuve_connect_agents/desktop/platform_adapters/macos/IuVe Connect Agent.app"
fi
if [ ! -d "$SRC_APP" ]; then
  printf '%s\n' "{\"ok\":false,\"error\":\"app_bundle_missing\",\"hint\":\"Expected IuVe Connect Agent.app next to install_console_app.sh\"}"
  exit 1
fi

USER_APPS="${HOME}/Applications"
DEST_APP="$USER_APPS/IuVe Connect Agent.app"
OPT_APPS="$AGENT_ROOT/Applications"
mkdir -p "$USER_APPS" "$OPT_APPS" "${HOME}/.config/iuve-connect-agent"
mkdir -p "${HOME}/Library/Logs/IuVeConnectAgent"
mkdir -p "${HOME}/Library/LaunchAgents"

# Stage under agent root for packaging /opt layout
rm -rf "$OPT_APPS/IuVe Connect Agent.app"
cp -R "$SRC_APP" "$OPT_APPS/IuVe Connect Agent.app"
chmod 0755 "$OPT_APPS/IuVe Connect Agent.app/Contents/MacOS/IuVeConnectAgent"
printf '%s\n' "$AGENT_ROOT" > "$OPT_APPS/IuVe Connect Agent.app/Contents/Resources/agent_root.path"

# User-visible Dock / Spotlight entry
rm -rf "$DEST_APP"
cp -R "$OPT_APPS/IuVe Connect Agent.app" "$DEST_APP"
chmod 0755 "$DEST_APP/Contents/MacOS/IuVeConnectAgent"

# LaunchAgent for headless run (does not open Console)
PLIST_TEMPLATE="$SCRIPT_DIR/launchd/eu.iuve.connect.desktop-agent.plist"
PLIST_DEST="${HOME}/Library/LaunchAgents/eu.iuve.connect.desktop-agent.plist"
if [ -f "$PLIST_TEMPLATE" ]; then
  sed \
    -e "s|__AGENT_ROOT__|${AGENT_ROOT}|g" \
    -e "s|__HOME__|${HOME}|g" \
    -e "s|__LOG_DIR__|${HOME}/Library/Logs/IuVeConnectAgent|g" \
    "$PLIST_TEMPLATE" > "$PLIST_DEST"
  if command -v launchctl >/dev/null 2>&1; then
    launchctl bootout "gui/$(id -u)/eu.iuve.connect.desktop-agent" >/dev/null 2>&1 || true
    launchctl bootstrap "gui/$(id -u)" "$PLIST_DEST" >/dev/null 2>&1 || \
      launchctl load -w "$PLIST_DEST" >/dev/null 2>&1 || true
  fi
fi

printf '%s\n' "{\"ok\":true,\"phase\":\"C.3\",\"ui_surface\":\"native_console\",\"agent_root\":\"${AGENT_ROOT}\",\"app\":\"${DEST_APP}\",\"opt_app\":\"${OPT_APPS}/IuVe Connect Agent.app\",\"launch_agent\":\"${PLIST_DEST}\"}"
