#!/bin/bash
# EMERGENCY FIX: Stop Watchtower crash loop caused by invalid Shoutrrr URL format
# The issue: Used http:// instead of ntfy:// - Shoutrrr doesn't recognize "http" as a service

set -e

echo "🚨 EMERGENCY: Fixing Watchtower crash loop"
echo "=========================================="
echo "Issue: Invalid notification URL format causing crash loop"
echo "Error: 'unknown service \"http\"' - Shoutrrr needs ntfy:// format"
echo

# Check if running as root/sudo
if [[ $EUID -ne 0 ]]; then
   echo "❌ This script must be run as root or with sudo"
   exit 1
fi

echo "🛑 Stopping crashed Watchtower container..."
docker stop watchtower 2>/dev/null || echo "Container already stopped"

echo "🗑️  Removing crashed container..."
docker rm watchtower 2>/dev/null || echo "Container already removed"

echo "🔧 Creating new Watchtower with CORRECT notification URL format..."
echo "   Using: ntfy://localhost:8081/updates?insecure=yes"
echo "   (This forces HTTP instead of HTTPS for local ntfy server)"

docker run -d \
  --name watchtower \
  --restart unless-stopped \
  -p 8091:8080 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -e WATCHTOWER_CLEANUP=true \
  -e WATCHTOWER_SCHEDULE="0 0 4 * * *" \
  -e WATCHTOWER_INCLUDE_STOPPED=false \
  -e TZ=America/Los_Angeles \
  -e WATCHTOWER_HTTP_API_UPDATE=true \
  -e WATCHTOWER_HTTP_API_TOKEN="REDACTED_HTTP_TOKEN" \
  -e WATCHTOWER_HTTP_API_METRICS=true \
  -e WATCHTOWER_NOTIFICATIONS=shoutrrr \
  -e WATCHTOWER_NOTIFICATION_URL="ntfy://localhost:8081/updates?insecure=yes" \
  containrrr/watchtower:latest

echo "⏳ Waiting for container to start..."
sleep 5

if docker ps --format '{{.Names}}\t{{.Status}}' | grep watchtower | grep -q "Up"; then
    echo "✅ Watchtower is now running successfully!"

    echo "🧪 Testing notification (this will trigger an update check)..."
    sleep 2
    curl -s -H "Authorization: Bearer watchtower-update-token" \
         -X POST http://localhost:8091/v1/update >/dev/null 2>&1 || echo "API call completed"

    sleep 3
    echo "📋 Recent logs:"
    docker logs watchtower --since 10s | tail -5

    if docker logs watchtower --since 10s | grep -q "unknown service"; then
        echo "❌ Still having issues - check logs above"
    else
        echo "✅ No more 'unknown service' errors detected!"
    fi
else
    echo "❌ Watchtower failed to start - check logs:"
    docker logs watchtower
fi

echo
echo "📝 WHAT WAS FIXED:"
echo "  ❌ OLD (BROKEN): http://localhost:8081/updates"
echo "  ✅ NEW (WORKING): ntfy://localhost:8081/updates?insecure=yes"
echo
echo "🔍 The issue was using http:// instead of ntfy:// protocol"
echo "   Shoutrrr notification system requires ntfy:// format"
echo "   The ?insecure=yes parameter forces HTTP instead of HTTPS"
echo
echo "🔧 Repository files have been updated with the correct format"
echo "✅ Emergency fix complete!"
