#!/usr/bin/env sh
set -eu

APP_DIR="${APP_DIR:-$HOME/Library/Application Support/MettricNetworkAgent}"
PLIST="$HOME/Library/LaunchAgents/io.mettric.network-agent.plist"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ARCH="$(uname -m)"

mkdir -p "$APP_DIR"
if [ "$ARCH" = "arm64" ]; then
  cp "$SCRIPT_DIR/mna-darwin-arm64" "$APP_DIR/mna"
else
  cp "$SCRIPT_DIR/mna-darwin-amd64" "$APP_DIR/mna"
fi
chmod +x "$APP_DIR/mna"
cp "$SCRIPT_DIR/config.yaml" "$APP_DIR/config.yaml"

cat > "$PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>io.mettric.network-agent</string>
  <key>ProgramArguments</key>
  <array>
    <string>$APP_DIR/mna</string>
    <string>--config</string>
    <string>$APP_DIR/config.yaml</string>
    <string>--local-dashboard</string>
    <string>--send</string>
  </array>
  <key>WorkingDirectory</key>
  <string>$APP_DIR</string>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$APP_DIR/agent.log</string>
  <key>StandardErrorPath</key>
  <string>$APP_DIR/agent.err.log</string>
</dict>
</plist>
PLIST

launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"

echo "Mettric Agent instalado."
echo "Dashboard local: http://127.0.0.1:9090"
