#!/bin/bash

# Emergency Watchtower Fix v2 - Correct ntfy URL format
# Based on Shoutrrr documentation for ntfy service

API_KEY=REDACTED_API_KEY
BASE_URL="http://vishinator.synology.me:10000"

echo "🚨 EMERGENCY FIX v2: Correcting ntfy notification URL format"
echo "============================================================="

# Function to fix Watchtower with correct ntfy URL
fix_watchtower_v2() {
  local endpoint_id=$1
  local endpoint_name=$2

  echo ""
  echo "🔧 Fixing Watchtower on: $endpoint_name (ID: $endpoint_id)"
  echo "--------------------------------------------------------"

  # Get current Watchtower container
  container_info=$(curl -s -H "X-API-Key: $API_KEY" \
    "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/json?all=true" | \
    jq -r '.[] | select(.Names[]? | contains("watchtower")) | "\(.Id) \(.Names[0]) \(.State)"')

  if [ -z "$container_info" ]; then
    echo "❌ No Watchtower container found"
    return 1
  fi

  read container_id container_name state <<< "$container_info"
  echo "📍 Found container: $container_name ($container_id) - State: $state"

  # Stop and remove current container
  echo "🛑 Stopping and removing current container..."
  curl -s -X POST -H "X-API-Key: $API_KEY" \
    "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$container_id/stop" > /dev/null

  sleep 2

  curl -s -X DELETE -H "X-API-Key: $API_KEY" \
    "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$container_id?force=true" > /dev/null

  sleep 2

  # Use correct ntfy URL format - no insecure parameter, just HTTP scheme
  # For local HTTP ntfy servers, use http:// in the host part
  if [ "$endpoint_name" = "Atlantis" ] || [ "$endpoint_name" = "Calypso" ]; then
    # For local ntfy servers, we need to use the generic HTTP format
    # Since ntfy:// defaults to HTTPS, we'll use generic:// for HTTP
    NOTIFICATION_URL="generic+http://localhost:8081/updates"
  else
    NOTIFICATION_URL="ntfy://ntfy.vish.gg/REDACTED_NTFY_TOPIC"
  fi

  echo "🔗 Using notification URL: $NOTIFICATION_URL"

  # Create new container with corrected URL
  create_response=$(curl -s -X POST -H "X-API-Key: $API_KEY" \
    -H "Content-Type: application/json" \
    "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/create?name=watchtower" \
    -d "{
      \"Image\": \"containrrr/watchtower:latest\",
      \"Env\": [
        \"WATCHTOWER_CLEANUP=true\",
        \"WATCHTOWER_INCLUDE_RESTARTING=true\",
        \"WATCHTOWER_INCLUDE_STOPPED=true\",
        \"WATCHTOWER_REVIVE_STOPPED=false\",
        \"WATCHTOWER_POLL_INTERVAL=3600\",
        \"WATCHTOWER_TIMEOUT=10s\",
        \"WATCHTOWER_HTTP_API_UPDATE=true\",
        \"WATCHTOWER_HTTP_API_TOKEN="REDACTED_HTTP_TOKEN"\",
        \"WATCHTOWER_NOTIFICATIONS=shoutrrr\",
        \"WATCHTOWER_NOTIFICATION_URL=$NOTIFICATION_URL\",
        \"TZ=America/Los_Angeles\"
      ],
      \"HostConfig\": {
        \"Binds\": [\"/var/run/docker.sock:/var/run/docker.sock\"],
        \"RestartPolicy\": {\"Name\": \"always\"},
        \"PortBindings\": {\"8080/tcp\": [{\"HostPort\": \"8080\"}]}
      }
    }")

  new_container_id=$(echo "$create_response" | jq -r '.Id')

  if [ "$new_container_id" != "null" ] && [ -n "$new_container_id" ]; then
    echo "✅ Created new container: ${new_container_id:0:12}"

    # Start the container
    echo "▶️  Starting new Watchtower container..."
    start_response=$(curl -s -X POST -H "X-API-Key: $API_KEY" \
      "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$new_container_id/start")

    sleep 5

    # Check status
    container_status=$(curl -s -H "X-API-Key: $API_KEY" \
      "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$new_container_id/json" | \
      jq -r '.State.Status')

    echo "📊 Container status: $container_status"

    if [ "$container_status" = "running" ]; then
      echo "🟢 SUCCESS: Watchtower is running!"

      # Check logs for any errors
      echo "📋 Recent logs:"
      curl -s -H "X-API-Key: $API_KEY" \
        "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$new_container_id/logs?stdout=true&stderr=true&tail=3" | \
        sed 's/^.......//g' | sed 's/^/   /'
    else
      echo "🔴 Issue: Container status is $container_status"
      echo "📋 Logs for debugging:"
      curl -s -H "X-API-Key: $API_KEY" \
        "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$new_container_id/logs?stdout=true&stderr=true&tail=5" | \
        sed 's/^.......//g' | sed 's/^/   /'
    fi
  else
    echo "🔴 FAILED: Could not create container"
    echo "API Response: $create_response"
  fi
}

# Fix both endpoints
fix_watchtower_v2 2 "Atlantis"
fix_watchtower_v2 443397 "Calypso"

echo ""
echo "============================================================="
echo "🎯 Fix v2 complete! Checking final status..."
echo "============================================================="

# Quick status check
sleep 3
./scripts/check-watchtower-status.sh
