#!/bin/bash

set -e

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

echo -e "${BLUE}🧪 Testing Debian package structure...${NC}"

# Check if we're in the right directory
if [ ! -f "debian/control" ]; then
    echo -e "${RED}❌ Not in a Debian package directory (debian/control not found)${NC}"
    exit 1
fi

# Clean previous builds
echo -e "${YELLOW}🧹 Cleaning previous builds...${NC}"
rm -rf debian/tmp debian/sesterce-cli

# Build the application
echo -e "${YELLOW}🔨 Building application...${NC}"
npm ci
npm run build:ci

# Test the debian/rules install step
echo -e "${YELLOW}📦 Testing debian/rules install step...${NC}"
make -f debian/rules override_dh_auto_install

# Check if files were installed correctly
echo -e "${YELLOW}🔍 Checking installed files...${NC}"

# Check usr/bin/sesterce
if [ -L "debian/tmp/usr/bin/sesterce" ]; then
    echo -e "${GREEN}✅ usr/bin/sesterce symlink created${NC}"
    echo "   Target: $(readlink debian/tmp/usr/bin/sesterce)"
else
    echo -e "${RED}❌ usr/bin/sesterce symlink not found${NC}"
fi

# Check usr/lib/sesterce-cli directory
if [ -d "debian/tmp/usr/lib/sesterce-cli" ]; then
    echo -e "${GREEN}✅ usr/lib/sesterce-cli directory created${NC}"
    
    # Check for key files
    if [ -f "debian/tmp/usr/lib/sesterce-cli/package.json" ]; then
        echo -e "${GREEN}✅ package.json copied${NC}"
    else
        echo -e "${RED}❌ package.json not found${NC}"
    fi
    
    if [ -d "debian/tmp/usr/lib/sesterce-cli/node_modules" ]; then
        echo -e "${GREEN}✅ node_modules copied${NC}"
    else
        echo -e "${RED}❌ node_modules not found${NC}"
    fi
    
    if [ -d "debian/tmp/usr/lib/sesterce-cli/cli" ]; then
        echo -e "${GREEN}✅ cli directory copied${NC}"
    else
        echo -e "${RED}❌ cli directory not found${NC}"
    fi
else
    echo -e "${RED}❌ usr/lib/sesterce-cli directory not found${NC}"
fi

# Test dh_install
echo -e "${YELLOW}🔍 Testing dh_install...${NC}"
if command -v dh_install &> /dev/null; then
    # Run dh_install in dry-run mode if possible
    if dh_install --help 2>&1 | grep -q "dry-run"; then
        dh_install --dry-run
        echo -e "${GREEN}✅ dh_install dry-run completed${NC}"
    else
        echo -e "${YELLOW}⚠️ dh_install dry-run not available, skipping${NC}"
    fi
else
    echo -e "${YELLOW}⚠️ dh_install not available (not on Debian/Ubuntu)${NC}"
fi

echo -e "${GREEN}✅ Debian package structure test completed!${NC}" 