#!/usr/bin/env bash
# openclaw-watchdog installer (Krilly's fork — Telegram + Gotify edition)
# https://github.com/jlgrimes/openclaw-watchdog
set -euo pipefail

INSTALL_DIR="$HOME/.openclaw"
SERVICE_NAME="openclaw-watchdog"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "🦞 OpenClaw Watchdog — Installer (Krilly's Telegram/Gotify Edition)"
echo "───────────────────────────────────────────────────────────────────"

# Ensure install dir exists
mkdir -p "$INSTALL_DIR"

# Copy watchdog script
cp "$SCRIPT_DIR/watchdog.sh" "$INSTALL_DIR/watchdog.sh"
chmod +x "$INSTALL_DIR/watchdog.sh"
echo "✅ Installed watchdog.sh → $INSTALL_DIR/watchdog.sh"

# Prompt for Telegram bot token
TELEGRAM_BOT_TOKEN=""
read -rp "Telegram Bot Token (leave blank to skip): " TELEGRAM_BOT_TOKEN

# Prompt for Gotify token
GOTIFY_TOKEN=""
read -rp "Gotify Token (leave blank to skip): " GOTIFY_TOKEN

# Prompt for custom Gotify URL
GOTIFY_URL="http://runtipi.kangaroo-eel.ts.net:8129"
read -rp "Gotify URL [$GOTIFY_URL]: " custom_gotify
[[ -n "$custom_gotify" ]] && GOTIFY_URL="$custom_gotify"

# Create env file
ENV_FILE="$INSTALL_DIR/watchdog.env"
cat > "$ENV_FILE" <<EOF
# OpenClaw Watchdog Configuration
# Edit these values as needed, then restart the service:
#   sudo systemctl restart $SERVICE_NAME

HEALTH_URL=http://localhost:3000/health
CHECK_INTERVAL=30
FAIL_THRESHOLD=3
OPENCLAW_CONFIG_PATH=$HOME/.openclaw/config.yaml

# Notification Settings
TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
TELEGRAM_CHAT=1793951355
GOTIFY_URL=${GOTIFY_URL}
GOTIFY_TOKEN=${GOTIFY_TOKEN}

# Legacy Discord (optional)
# DISCORD_CHANNEL_ID=
# DISCORD_BOT_TOKEN=
EOF
chmod 600 "$ENV_FILE"
echo "✅ Created config → $ENV_FILE"

# Create systemd service
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
sudo tee "$SERVICE_FILE" >/dev/null <<EOF
[Unit]
Description=OpenClaw Watchdog — Gateway health monitor & auto-recovery
After=network.target

[Service]
Type=simple
User=$USER
EnvironmentFile=$ENV_FILE
ExecStart=/usr/bin/env bash $INSTALL_DIR/watchdog.sh
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

echo "✅ Created systemd service → $SERVICE_FILE"

# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE_NAME"
sudo systemctl start "$SERVICE_NAME"

echo ""
echo "🎉 Watchdog is running!"
echo ""
echo "  Status:   sudo systemctl status $SERVICE_NAME"
echo "  Logs:     tail -f $INSTALL_DIR/watchdog.log"
echo "  Config:   $ENV_FILE"
echo ""
echo "You'll get alerts via:"
[[ -n "$TELEGRAM_BOT_TOKEN" ]] && echo "  ✅ Telegram"
[[ -n "$GOTIFY_TOKEN" ]] && echo "  ✅ Gotify ($GOTIFY_URL)"
