#!/bin/bash

# Watchtower Status Checker via Portainer API
# Checks all endpoints for Watchtower containers and their health

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

echo "🔍 Checking Watchtower containers across all endpoints..."
echo "=================================================="

# Function to check containers on an endpoint
check_watchtower() {
  local endpoint_id=$1
  local endpoint_name=$2

  echo ""
  echo "📍 Endpoint: $endpoint_name (ID: $endpoint_id)"
  echo "----------------------------------------"

  # Get containers with "watchtower" in the name
  containers=$(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[0:12]) \(.Names[0]) \(.State) \(.Status)"')

  if [ -z "$containers" ]; then
    echo "❌ No Watchtower containers found"
  else
    echo "✅ Watchtower containers found:"
    echo "$containers" | while read id name state status; do
      echo "   Container: $name"
      echo "   ID: $id"
      echo "   State: $state"
      echo "   Status: $status"

      # Check if container is running
      if [ "$state" = "running" ]; then
        echo "   🟢 Status: HEALTHY"

        # Get recent logs to check for errors
        echo "   📋 Recent logs (last 10 lines):"
        curl -s -H "X-API-Key: $API_KEY" \
          "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$id/logs?stdout=true&stderr=true&tail=10" | \
          sed 's/^.......//g' | tail -5 | sed 's/^/      /'
      else
        echo "   🔴 Status: NOT RUNNING"

        # Get logs to see why it stopped
        echo "   📋 Last logs before stopping:"
        curl -s -H "X-API-Key: $API_KEY" \
          "$BASE_URL/api/endpoints/$endpoint_id/docker/containers/$id/logs?stdout=true&stderr=true&tail=10" | \
          sed 's/^.......//g' | tail -5 | sed 's/^/      /'
      fi
      echo ""
    done
  fi
}

# Get all endpoints and check each one
echo "Getting endpoint list..."
endpoints=$(curl -s -H "X-API-Key: $API_KEY" "$BASE_URL/api/endpoints" | \
  jq -r '.[] | "\(.Id) \(.Name) \(.Status)"')

echo "$endpoints" | while read id name status; do
  if [ "$status" = "1" ]; then
    check_watchtower "$id" "$name"
  else
    echo ""
    echo "📍 Endpoint: $name (ID: $id)"
    echo "----------------------------------------"
    echo "⚠️  Endpoint is OFFLINE (Status: $status)"
  fi
done

echo ""
echo "=================================================="
echo "✅ Watchtower status check complete!"
