#!/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 build process...${NC}"

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

# Install dependencies
echo -e "${YELLOW}📦 Installing dependencies...${NC}"
npm ci

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

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

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

# Wait a moment for file operations to complete
sleep 1

# Verify the package structure
echo -e "${YELLOW}🔍 Verifying package structure...${NC}"

# Check if all required files are present
REQUIRED_FILES=(
    "debian/tmp/usr/bin/sesterce"
    "debian/tmp/usr/lib/sesterce-cli/package.json"
    "debian/tmp/usr/lib/sesterce-cli/cli/app.js"
    "debian/tmp/usr/lib/sesterce-cli/node_modules"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ -e "$file" ] || [ -L "$file" ]; then
        echo -e "${GREEN}✅ $file exists${NC}"
    else
        echo -e "${RED}❌ $file missing${NC}"
        echo "Debug: ls -la $(dirname "$file")"
        ls -la "$(dirname "$file")" 2>/dev/null || echo "Directory not found"
        exit 1
    fi
done

# Check if the symlink is correct
if [ -L "debian/tmp/usr/bin/sesterce" ]; then
    TARGET=$(readlink debian/tmp/usr/bin/sesterce)
    if [ "$TARGET" = "/usr/lib/sesterce-cli/cli/app.js" ]; then
        echo -e "${GREEN}✅ Symlink target is correct: $TARGET${NC}"
    else
        echo -e "${RED}❌ Symlink target is incorrect: $TARGET${NC}"
        exit 1
    fi
else
    echo -e "${RED}❌ Symlink not found${NC}"
    exit 1
fi

# Check if the main CLI file is executable
if [ -x "debian/tmp/usr/lib/sesterce-cli/cli/app.js" ]; then
    echo -e "${GREEN}✅ Main CLI file is executable${NC}"
else
    echo -e "${RED}❌ Main CLI file is not executable${NC}"
    exit 1
fi

# Test that the CLI can be executed
echo -e "${YELLOW}🧪 Testing CLI execution...${NC}"
if node debian/tmp/usr/lib/sesterce-cli/cli/app.js --help > /dev/null 2>&1; then
    echo -e "${GREEN}✅ CLI executes successfully${NC}"
else
    echo -e "${YELLOW}⚠️ CLI execution test skipped (may require full environment)${NC}"
fi

echo -e "${GREEN}✅ Debian package build test completed successfully!${NC}"
echo -e "${BLUE}📦 The package structure is ready for dpkg-buildpackage${NC}" 