#!/bin/bash

set -e

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

echo -e "${GREEN}Testing Debian package for Sesterce CLI...${NC}"

# Check if we're on a Debian-based system
if ! command -v dpkg &> /dev/null; then
    echo -e "${RED}Error: This script requires a Debian-based system (Ubuntu, Debian, etc.)${NC}"
    exit 1
fi

# Find the latest Debian package
PACKAGE_FILE=$(ls -t ../sesterce-cli_*_all.deb 2>/dev/null | head -1)

if [ -z "$PACKAGE_FILE" ]; then
    echo -e "${RED}Error: No Debian package found. Please build the package first.${NC}"
    exit 1
fi

echo -e "${YELLOW}Found package: $PACKAGE_FILE${NC}"

# Check package contents
echo -e "${YELLOW}Checking package contents...${NC}"
dpkg -c "$PACKAGE_FILE"

# Check package information
echo -e "${YELLOW}Package information:${NC}"
dpkg -I "$PACKAGE_FILE"

# Test installation in a temporary directory
echo -e "${YELLOW}Testing package installation...${NC}"
TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR"

# Extract package
dpkg-deb -R "$PACKAGE_FILE" .

# Check if the binary is executable
if [ -f "usr/bin/sesterce" ]; then
    echo -e "${GREEN}✓ Binary found at usr/bin/sesterce${NC}"
    ls -la usr/bin/sesterce
else
    echo -e "${RED}✗ Binary not found at usr/bin/sesterce${NC}"
fi

# Check if application files are present
if [ -d "usr/lib/sesterce-cli" ]; then
    echo -e "${GREEN}✓ Application files found at usr/lib/sesterce-cli${NC}"
    ls -la usr/lib/sesterce-cli/
else
    echo -e "${RED}✗ Application files not found at usr/lib/sesterce-cli${NC}"
fi

# Check dependencies
echo -e "${YELLOW}Package dependencies:${NC}"
dpkg -I "$PACKAGE_FILE" | grep -E "^ Depends:"

# Cleanup
cd - > /dev/null
rm -rf "$TEMP_DIR"

echo -e "${GREEN}Package test completed successfully!${NC}"
echo -e "${YELLOW}To install the package: sudo dpkg -i $PACKAGE_FILE${NC}" 