#!/bin/bash

# apt-ostree Debian Package Builder
# Simplified version for CI/CD environments

set -e

# Colors for output
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}"
}

# Configuration
PROJECT_NAME="apt-ostree"
VERSION="0.1.0"

print_header "apt-ostree Debian Package Builder"

# 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

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

print_status "Building apt-ostree package..."

# Ensure Rust environment is available
if command -v cargo &> /dev/null; then
    print_status "Rust environment found"
    cargo --version
else
    print_error "Cargo not found. Please ensure Rust is installed."
    exit 1
fi

# Build the package using dpkg-buildpackage
print_status "Running dpkg-buildpackage..."
dpkg-buildpackage -us -uc -b

# Check if build was successful
if [ $? -eq 0 ]; then
    print_success "Package built successfully!"
    
    # List built packages
    print_status "Built packages:"
    ls -la ../*.deb 2>/dev/null || echo "No .deb files found in parent directory"
    ls -la *.deb 2>/dev/null || echo "No .deb files found in current directory"
    
else
    print_error "Package build failed!"
    exit 1
fi

print_success "Build completed successfully!" 