#!/bin/bash

# Test Debian Package Build for apt-ostree
# This script tests the debian packaging locally before CI/CD

set -e

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

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo ""
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}================================${NC}"
}

print_header "Testing apt-ostree Debian Package Build"

# Check if we're in the right directory
if [ ! -f "Cargo.toml" ]; then
    print_error "Cargo.toml not found. Please run this script from the project root."
    exit 1
fi

if [ ! -d "debian" ]; then
    print_error "debian/ directory not found. Please ensure Debian packaging files are present."
    exit 1
fi

# Check prerequisites
print_status "Checking prerequisites..."

for cmd in cargo rustc dpkg-buildpackage; do
    if ! command -v $cmd &> /dev/null; then
        print_error "$cmd not found. Please install required build tools."
        exit 1
    fi
done

print_success "All prerequisites found"

# Clean previous builds
print_status "Cleaning previous builds..."
rm -rf debian/cargo target/release *.deb ../*.deb
print_success "Cleanup completed"

# Test cargo build
print_status "Testing cargo build..."
cargo build --release
print_success "Cargo build successful"

# Test debian package build
print_status "Testing debian package build..."
dpkg-buildpackage -us -uc -b
print_success "Debian package build successful"

# Check for built packages
print_status "Checking built packages..."
if ls -1 ../*.deb 2>/dev/null | grep -q apt-ostree; then
    print_success "apt-ostree package found"
    ls -la ../*.deb
else
    print_error "No apt-ostree package found"
    exit 1
fi

# Test package installation (optional)
read -p "Do you want to test package installation? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_status "Testing package installation..."
    sudo dpkg -i ../apt-ostree_*.deb
    sudo apt-get install -f -y
    
    # Test installed binary
    if command -v apt-ostree &> /dev/null; then
        print_success "apt-ostree installed successfully"
        apt-ostree --version
    else
        print_error "apt-ostree not found after installation"
        exit 1
    fi
fi

print_header "Test Complete!"
print_success "Debian package build test passed!"
print_status "Ready for CI/CD deployment" 