#!/bin/sh
CONFIG="${JOPLIN_WEBDAV_CONFIG:-$HOME/.config/joplin-webdav/env}"
PID_FILE="$HOME/.config/joplin-webdav/rclone.pid"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)

echo "=== WebDAV Joplin ==="
if [ -f "$CONFIG" ]; then
  # shellcheck disable=SC1090
  . "$CONFIG"
  echo "Пользователь: ${JOPLIN_WEBDAV_USER:-?}"
  echo "Порт:         ${JOPLIN_WEBDAV_PORT:-8080}"
  echo "Папка:        ${JOPLIN_WEBDAV_ROOT:-$HOME/JoplinSync}"
else
  echo "Конфиг не найден: $CONFIG"
fi

echo ""
echo "=== Процесс ==="
if pgrep -f "rclone serve webdav" >/dev/null 2>&1; then
  pgrep -lf "rclone serve webdav" 2>/dev/null || true
else
  echo "Не запущен → ./docs/apps/joplin/scripts/joplin-webdav-serve.sh"
fi

port="${JOPLIN_WEBDAV_PORT:-8080}"

echo ""
echo "=== URL для телефона (Android-хотспот) ==="
if [ -x "$SCRIPT_DIR/joplin-hotspot-alias.sh" ]; then
  "$SCRIPT_DIR/joplin-hotspot-alias.sh" status
else
  echo "(нет joplin-hotspot-alias.sh)"
fi

echo ""
echo "=== mDNS (.local) — с телефона НЕ работает ==="
if [ -x "$SCRIPT_DIR/joplin-mdns-setup.sh" ]; then
  host="$(scutil --get LocalHostName 2>/dev/null | tr '[:upper:]' '[:lower:]' || echo '?')"
  echo "http://${host}.local:${port} — только Mac/Windows; Android-хотспот не резолвит"
fi

echo ""
echo "=== IP Mac (DHCP, справочно) ==="
ip=$(ipconfig getifaddr en0 2>/dev/null || true)
[ -n "$ip" ] && echo "primary en0: $ip" || echo "нет IP"

echo ""
echo "=== Порт :8080 ==="
lsof -nP -iTCP:"$port" -sTCP:LISTEN 2>/dev/null || echo "не слушает"

echo ""
echo "=== URL в Joplin (Mac) ==="
settings="$HOME/.config/joplin-desktop/settings.json"
if [ -f "$settings" ]; then
  grep -o '"sync\.6\.path": *"[^"]*"' "$settings" 2>/dev/null | sed 's/.*"\(http[^"]*\)".*/\1/' \
    | while read -r u; do echo "settings.json: $u"; done
fi

echo ""
echo "=== rclone (запросы с телефона?) ==="
log="$HOME/Library/Logs/joplin-webdav/rclone.log"
if [ -f "$log" ]; then
  phone_lines=$(grep -E 'from 10\.|from 192\.168\.' "$log" 2>/dev/null | tail -3)
  if [ -n "$phone_lines" ]; then
    echo "$phone_lines"
  else
    echo "нет запросов с LAN (только 127.0.0.1?) — телефон не достучался"
  fi
fi

echo ""
echo "=== Учётка ==="
[ -f "$CONFIG" ] && echo "Пароль: $CONFIG → JOPLIN_WEBDAV_PASS"
