#!/bin/sh
# Установка: конфиг, launchd (автозапуск), первый старт WebDAV.
set -e

ROOT="$(CDPATH= cd -- "$(dirname "$0")" && pwd)"
CONFIG_DIR="$HOME/.config/joplin-webdav"
CONFIG="$CONFIG_DIR/env"
LAUNCH_AGENT="$HOME/Library/LaunchAgents/com.eternal.joplin-webdav.plist"
SERVE="$ROOT/joplin-webdav-serve.sh"

mkdir -p "$CONFIG_DIR" "$HOME/JoplinSync" "$HOME/Library/Logs/joplin-webdav"

if [ ! -f "$CONFIG" ]; then
  PASS=$(openssl rand -base64 18 | tr -d '/+=' | head -c 24)
  cat > "$CONFIG" <<EOF
# Локальный WebDAV для Joplin. Только LAN. Не коммитить.
JOPLIN_WEBDAV_USER=joplin
JOPLIN_WEBDAV_PASS=$PASS
JOPLIN_WEBDAV_PORT=8080
JOPLIN_WEBDAV_ROOT=$HOME/JoplinSync
# Опционально (legacy alias *.100 — не нужен при mDNS):
# JOPLIN_STATIC_IP=10.219.227.100
# JOPLIN_MDNS_HOST=joplin-mac
# JOPLIN_PHONE_URL=http://joplin-mac.local:8080
EOF
  chmod 600 "$CONFIG"
  echo "Создан $CONFIG"
else
  echo "Конфиг уже есть: $CONFIG"
fi

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

if ! command -v rclone >/dev/null 2>&1; then
  echo "Устанавливаю rclone..."
  brew install rclone
fi

mkdir -p "$HOME/Library/LaunchAgents"
cat > "$LAUNCH_AGENT" <<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-webdav</string>
  <key>ProgramArguments</key>
  <array>
    <string>$SERVE</string>
    <string>--foreground</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$HOME/Library/Logs/joplin-webdav/launchd.out.log</string>
  <key>StandardErrorPath</key>
  <string>$HOME/Library/Logs/joplin-webdav/launchd.err.log</string>
</dict>
</plist>
EOF

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

launchctl enable "gui/$(id -u)/com.eternal.joplin-webdav" 2>/dev/null || true

chmod +x "$ROOT"/joplin-mdns-setup.sh 2>/dev/null || true
if [ -x "$ROOT/joplin-mdns-setup.sh" ]; then
  echo ""
  echo "=== mDNS (стабильный URL на телефоне) ==="
  if [ "$(scutil --get LocalHostName 2>/dev/null)" = "joplin-mac" ]; then
    "$ROOT/joplin-mdns-setup.sh" status || true
  else
    echo "LocalHostName ещё не joplin-mac. Один раз:"
    echo "  $ROOT/joplin-mdns-setup.sh install"
  fi
fi

sleep 2
"$ROOT/joplin-webdav-status.sh"

echo ""
echo "Пароль для Joplin:"
grep JOPLIN_WEBDAV_PASS "$CONFIG" | cut -d= -f2-
echo ""
echo "На телефоне (один раз, навсегда): http://joplin-mac.local:8080"
echo "Установка имени: $ROOT/joplin-mdns-setup.sh install"
