#!/bin/bash

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}=== Registry Connectivity Test ===${NC}"
echo ""

REGISTRY="192.168.1.208:3002"
IMAGE="jason/socktop-webterm:0.2.0"

echo "Testing connection to Gitea registry at $REGISTRY"
echo ""

# Test 1: HTTP connectivity
echo -e "${YELLOW}Test 1: HTTP GET to /v2/${NC}"
if curl -f -s -m 5 "http://$REGISTRY/v2/" > /dev/null; then
    echo -e "${GREEN}✓ Registry API is accessible${NC}"
else
    echo -e "${RED}✗ Cannot access registry API${NC}"
    echo "Try: curl -v http://$REGISTRY/v2/"
fi
echo ""

# Test 2: Check if image exists
echo -e "${YELLOW}Test 2: Check if image exists${NC}"
RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" "http://$REGISTRY/v2/$IMAGE/manifests/0.2.0")
if [ "$RESPONSE" = "200" ] || [ "$RESPONSE" = "401" ]; then
    echo -e "${GREEN}✓ Image endpoint responds (HTTP $RESPONSE)${NC}"
else
    echo -e "${RED}✗ Image not found (HTTP $RESPONSE)${NC}"
fi
echo ""

# Test 3: Check /etc/rancher/k3s/registries.yaml
echo -e "${YELLOW}Test 3: Check registries.yaml${NC}"
if [ -f /etc/rancher/k3s/registries.yaml ]; then
    echo -e "${GREEN}✓ registries.yaml exists${NC}"
    echo "Content:"
    cat /etc/rancher/k3s/registries.yaml
else
    echo -e "${RED}✗ registries.yaml not found${NC}"
fi
echo ""

# Test 4: Check k3s service
echo -e "${YELLOW}Test 4: Check k3s service${NC}"
if systemctl is-active --quiet k3s; then
    echo -e "${GREEN}✓ k3s service is running${NC}"
elif systemctl is-active --quiet k3s-agent; then
    echo -e "${GREEN}✓ k3s-agent service is running${NC}"
else
    echo -e "${RED}✗ k3s service is not running${NC}"
fi
echo ""

# Test 5: Try docker pull (if docker is installed)
echo -e "${YELLOW}Test 5: Try docker pull${NC}"
if command -v docker &> /dev/null; then
    echo "Attempting docker pull (timeout 10s)..."
    timeout 10 docker pull "$REGISTRY/$IMAGE" 2>&1 | tail -5
else
    echo "Docker not installed, skipping"
fi
echo ""

echo -e "${BLUE}=== Recommendations ===${NC}"
echo ""
echo "If registry.yaml exists but pull hangs:"
echo "  1. Restart k3s: sudo systemctl restart k3s"
echo "  2. Check k3s logs: sudo journalctl -u k3s -n 50"
echo ""
echo "If image endpoint returns 401:"
echo "  - This is normal - registry requires auth"
echo "  - k3s should handle this automatically"
echo ""
