#!/usr/bin/env bash
# LaunchAgent: SOCKS на 1081 с выходом через DigitalOcean (прокси → DO), см. PROXY_GUIDE.md.
# Требуется блок Host telegram-socks-via-do в ~/.ssh/config.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLIST_NAME="com.hunab.telegram-socks-via-do.plist"
DST="$HOME/Library/LaunchAgents/$PLIST_NAME"

mkdir -p "$HOME/Library/LaunchAgents"
HUNAB_SUPPORT="$HOME/Library/Application Support/hunab"
mkdir -p "$HUNAB_SUPPORT"
cp "$SCRIPT_DIR/telegram-socks-launch.sh" "$HUNAB_SUPPORT/telegram-socks-launch.sh"
chmod +x "$HUNAB_SUPPORT/telegram-socks-launch.sh"
# Не использовать имя UID — в bash это readonly (присваивание ломает скрипт).
GUI_UID=$(id -u)
launchctl unload "$HOME/Library/LaunchAgents/com.hunab.telegram-socks.plist" 2>/dev/null || true
launchctl bootout "gui/$GUI_UID/com.hunab.telegram-socks-via-do" 2>/dev/null || true
launchctl unload "$DST" 2>/dev/null || true
cp "$SCRIPT_DIR/$PLIST_NAME" "$DST"
if launchctl bootstrap "gui/$GUI_UID" "$DST" 2>/dev/null; then
  :
else
  launchctl load "$DST" || true
fi
echo "Installed: $DST (loaded). Survives reboot while this plist exists."
echo "Launch helper: $HUNAB_SUPPORT/telegram-socks-launch.sh (only Mac→RU→DO via telegram-socks-via-do)."
echo "Ensure ~/.ssh/config defines Host telegram-socks-via-do (+ ProxyJump hsites-ahau) — PROXY_GUIDE.md / TELEGRAM_GUIDE.md."
echo "Verify autostart: launchctl list | grep telegram-socks"
lsof -i :1081 -sTCP:LISTEN 2>/dev/null && echo "Port 1081 is listening." || echo "Check in a few seconds: lsof -i :1081"
