#!/bin/sh
# LaunchAgent: каждые 60 с проверять primary *.100 (нужен joplin-hotspot-alias-install-sudo.sh).
set -e

ROOT="$(CDPATH= cd -- "$(dirname "$0")" && pwd)"
ALIAS="$ROOT/joplin-hotspot-alias.sh"
PLIST="$HOME/Library/LaunchAgents/com.eternal.joplin-hotspot-alias.plist"

chmod +x "$ROOT"/joplin-hotspot-alias*.sh

mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs/joplin-webdav"

cat >"$PLIST" <<EOF
<?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>com.eternal.joplin-hotspot-alias</string>
  <key>ProgramArguments</key>
  <array>
    <string>$ALIAS</string>
    <string>ensure</string>
  </array>
  <key>StartInterval</key>
  <integer>60</integer>
  <key>RunAtLoad</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$HOME/Library/Logs/joplin-webdav/alias-launchd.out.log</string>
  <key>StandardErrorPath</key>
  <string>$HOME/Library/Logs/joplin-webdav/alias-launchd.err.log</string>
</dict>
</plist>
EOF

launchctl bootout "gui/$(id -u)/com.eternal.joplin-hotspot-alias" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
launchctl enable "gui/$(id -u)/com.eternal.joplin-hotspot-alias" 2>/dev/null || true

echo "LaunchAgent com.eternal.joplin-hotspot-alias установлен (каждые 60 с)."
echo "Для работы без пароля один раз:"
echo "  $ROOT/joplin-hotspot-alias-install-sudo.sh"
echo "Сейчас:"
"$ALIAS" status
