#!/bin/bash
# Install telegram bot as a macOS launchd service (auto-start on boot)
set -e

BOT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$BOT_DIR")"
BUN_PATH="$(which bun)"
PLIST_NAME="com.cr.telegram-bot"
PLIST_PATH="$HOME/Library/LaunchAgents/${PLIST_NAME}.plist"

if [ -z "$BUN_PATH" ]; then
  echo "❌ bun not found in PATH"
  exit 1
fi

if [ ! -f "$PROJECT_DIR/.env" ]; then
  echo "❌ .env not found at $PROJECT_DIR/.env"
  exit 1
fi

# Unload if already installed
launchctl unload "$PLIST_PATH" 2>/dev/null || true

cat > "$PLIST_PATH" <<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>${PLIST_NAME}</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>-c</string>
        <string>set -a; source ${PROJECT_DIR}/.env; set +a; exec ${BUN_PATH} run ${BOT_DIR}/index.ts</string>
    </array>
    <key>WorkingDirectory</key>
    <string>${BOT_DIR}</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>${BOT_DIR}/bot.log</string>
    <key>StandardErrorPath</key>
    <string>${BOT_DIR}/bot.err</string>
</dict>
</plist>
EOF

launchctl load "$PLIST_PATH"
echo "✅ Installed and started: ${PLIST_NAME}"
echo "   Logs: ${BOT_DIR}/bot.log"
echo "   Stop: launchctl unload ${PLIST_PATH}"
