#!/bin/bash

# Cleanup script for orphaned test packages from getpkg testing
# This script removes test packages that start with "test-" from getpkg.xyz
# Run from the getpkg directory: bash cleanup_test_packages.sh

set -euo pipefail

GETPKG="./output/getpkg"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}Cleaning up orphaned test packages...${NC}"

# Check if getpkg binary exists
if [ ! -f "$GETPKG" ]; then
    echo -e "${RED}Error: getpkg binary not found at $GETPKG${NC}"
    echo "Please run ./build.sh first to build getpkg"
    exit 1
fi

# Check if SOS_WRITE_TOKEN is set
if [ -z "${SOS_WRITE_TOKEN:-}" ]; then
    echo -e "${RED}Error: SOS_WRITE_TOKEN environment variable is not set${NC}"
    echo "This token is required to unpublish packages from getpkg.xyz"
    exit 1
fi

echo "Using getpkg binary: $GETPKG"
echo "SOS_WRITE_TOKEN is set (${#SOS_WRITE_TOKEN} characters)"

# Get list of all packages from /dir endpoint
echo "Fetching package list from getpkg.xyz/dir..."
DIR_RESPONSE=$(curl -s "https://getpkg.xyz/dir" 2>/dev/null || echo "")

if [ -z "$DIR_RESPONSE" ]; then
    echo -e "${RED}Failed to fetch package list from server${NC}"
    exit 1
fi

# Extract test package labeltags from JSON response
# Try with jq first, fallback to grep/sed if jq is not available
if command -v jq >/dev/null 2>&1; then
    TEST_PACKAGES=$(echo "$DIR_RESPONSE" | jq -r '.entries[]?.labeltags[]? // empty' 2>/dev/null | grep "^test-" | sort -u || echo "")
else
    # Fallback: extract labeltags using grep and sed (less reliable but works without jq)
    TEST_PACKAGES=$(echo "$DIR_RESPONSE" | grep -o '"test-[^"]*"' | sed 's/"//g' | sort -u || echo "")
fi

if [ -z "$TEST_PACKAGES" ]; then
    echo -e "${GREEN}No test packages found to clean up${NC}"
    exit 0
fi

echo -e "\n${YELLOW}Found test packages to clean up:${NC}"
echo "$TEST_PACKAGES" | while read -r package; do
    echo "  - $package"
done

echo -e "\n${YELLOW}Cleaning up test packages...${NC}"

CLEANED_COUNT=0
FAILED_COUNT=0

# Use process substitution to avoid subshell issues
while IFS= read -r package; do
    if [ -n "$package" ]; then
        echo -n "Cleaning up $package... "
        
        # Try to unpublish the package (temporarily disable set -e)
        set +e
        $GETPKG unpublish "$package" >/dev/null 2>&1
        UNPUBLISH_RESULT=$?
        set -e
        
        if [ $UNPUBLISH_RESULT -eq 0 ]; then
            echo -e "${GREEN}OK${NC}"
            ((CLEANED_COUNT++))
        else
            echo -e "${RED}FAILED${NC}"
            ((FAILED_COUNT++))
        fi
    fi
done <<< "$TEST_PACKAGES"

echo -e "\n${YELLOW}Cleanup Summary:${NC}"
echo "Packages cleaned: $CLEANED_COUNT"
echo "Failed cleanups: $FAILED_COUNT"

if [ $FAILED_COUNT -eq 0 ]; then
    echo -e "${GREEN}All test packages cleaned up successfully!${NC}"
else
    echo -e "${YELLOW}Some packages failed to clean up. They may need manual removal.${NC}"
fi