#!/bin/bash

# === CONFIG ===
SERVER="root@chatwithus.live"
MASTODON_INSTANCE="https://chatwithus.live"
ACCESS_TOKEN="rimxBLi-eaJAcwagkmoj6UoW7Lc473tQY0cOM041Euw"
TOOT_TEXT="✅ ChatWithUs.Live services restarted from Krang via OPS script."
TOOT_VISIBILITY="unlisted"

TELEGRAM_BOT_TOKEN="8178867489:AAH0VjN7VnZSCIWasSz_y97iBLLjPJA751k"
TELEGRAM_CHAT_ID="1559582356"
TELEGRAM_TEXT="✅ Mastodon has been restarted by Krang. All services are back online."

LOG_FILE="/home/doc/genesis-tools/masto_restart.log"
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")

{
echo "[$TIMESTAMP] === Mastodon Restart Initiated ==="

# === Restart Mastodon Services ===
echo "[*] Connecting to $SERVER to restart Mastodon services..."

ssh "$SERVER" bash << 'EOF'
echo "Restarting mastodon-web..."
systemctl restart mastodon-web

echo "Restarting mastodon-sidekiq..."
systemctl restart mastodon-sidekiq

echo "Restarting mastodon-streaming..."
systemctl restart mastodon-streaming

echo "All services restarted."
EOF

# === Wait Until Mastodon API is Responsive ===
echo "[*] Waiting for Mastodon to come back online..."
until curl -sf "$MASTODON_INSTANCE/api/v1/instance" > /dev/null; do
    echo "   ... still starting up, retrying in 5s"
    sleep 5
done

echo "[+] Mastodon is back online."

# === Post Toot ===
echo "[*] Posting status to Mastodon..."
curl -s -X POST "$MASTODON_INSTANCE/api/v1/statuses" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -d "status=$TOOT_TEXT" \
  -d "visibility=$TOOT_VISIBILITY" > /dev/null && echo "[✓] Status posted."

# === Telegram Notification ===
echo "[*] Sending Telegram alert..."
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
  -d chat_id="$TELEGRAM_CHAT_ID" \
  -d text="$TELEGRAM_TEXT" > /dev/null && echo "[✓] Telegram alert sent."

echo "[✓] All tasks complete. Logged out of $SERVER."
echo "[$TIMESTAMP] === Mastodon Restart Complete ==="
echo ""

} >> "$LOG_FILE" 2>&1
