#!/bin/bash

set -e

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

# Function to print colored messages
print_error() {
    echo -e "${RED}ERROR: $1${NC}" >&2
}

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

print_info() {
    echo -e "${YELLOW}INFO: $1${NC}"
}

# Function to display usage
usage() {
    cat << EOF
Usage: $0 [OPTIONS] <package.deb>

Add a Debian package to the EveBox repository.

OPTIONS:
    -d, --distribution <dist>  Distribution (stable or unstable) [default: unstable]
    -a, --architecture <arch>  Architecture (amd64 or arm64) [auto-detected from package]
    -f, --force                Force addition even if package already exists
    -h, --help                 Display this help message

EXAMPLES:
    $0 evebox_0.18.0_amd64.deb
    $0 --distribution stable evebox_0.18.0_amd64.deb
    $0 -d unstable -f evebox_0.18.0_arm64.deb

EOF
    exit 1
}

# Default values
DISTRIBUTION="unstable"
ARCHITECTURE=""
FORCE=false
PACKAGE_FILE=""

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -d|--distribution)
            DISTRIBUTION="$2"
            shift 2
            ;;
        -a|--architecture)
            ARCHITECTURE="$2"
            shift 2
            ;;
        -f|--force)
            FORCE=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        -*)
            print_error "Unknown option: $1"
            usage
            ;;
        *)
            if [ -z "$PACKAGE_FILE" ]; then
                PACKAGE_FILE="$1"
            else
                print_error "Multiple package files specified"
                usage
            fi
            shift
            ;;
    esac
done

# Check if package file was provided
if [ -z "$PACKAGE_FILE" ]; then
    print_error "No package file specified"
    usage
fi

# Check if package file exists
if [ ! -f "$PACKAGE_FILE" ]; then
    print_error "Package file not found: $PACKAGE_FILE"
    exit 1
fi

# Validate distribution
if [[ "$DISTRIBUTION" != "stable" && "$DISTRIBUTION" != "unstable" ]]; then
    print_error "Invalid distribution: $DISTRIBUTION (must be 'stable' or 'unstable')"
    exit 1
fi

# Check if reprepro is installed
if ! command -v reprepro &> /dev/null; then
    print_info "reprepro is not installed. Installing..."
    sudo apt-get update
    sudo apt-get install -y reprepro
fi

# Extract package information
print_info "Extracting package information..."
PACKAGE_INFO=$(dpkg-deb --info "$PACKAGE_FILE" 2>/dev/null | grep -E "Package:|Version:|Architecture:")

if [ -z "$PACKAGE_INFO" ]; then
    print_error "Failed to extract package information from $PACKAGE_FILE"
    exit 1
fi

# Get package details
PKG_NAME=$(echo "$PACKAGE_INFO" | grep "Package:" | awk '{print $2}')
PKG_VERSION=$(echo "$PACKAGE_INFO" | grep "Version:" | awk '{print $2}')
PKG_ARCH=$(echo "$PACKAGE_INFO" | grep "Architecture:" | awk '{print $2}')

# Use detected architecture if not specified
if [ -z "$ARCHITECTURE" ]; then
    ARCHITECTURE="$PKG_ARCH"
fi

# Validate architecture
if [[ "$ARCHITECTURE" != "amd64" && "$ARCHITECTURE" != "arm64" && "$ARCHITECTURE" != "all" ]]; then
    print_error "Invalid architecture: $ARCHITECTURE (must be 'amd64', 'arm64', or 'all')"
    exit 1
fi

print_info "Package: $PKG_NAME"
print_info "Version: $PKG_VERSION"
print_info "Architecture: $ARCHITECTURE"
print_info "Distribution: $DISTRIBUTION"

# Check if repository structure exists
if [ ! -d "conf" ]; then
    print_error "Repository not initialized. Please run setup-repo.sh first."
    exit 1
fi

# Check if package already exists in the repository
if reprepro list "$DISTRIBUTION" "$PKG_NAME" 2>/dev/null | grep -q "$PKG_VERSION"; then
    if [ "$FORCE" = false ]; then
        print_error "Package $PKG_NAME version $PKG_VERSION already exists in $DISTRIBUTION"
        print_info "Use --force to overwrite"
        exit 1
    else
        print_info "Removing existing package..."
        reprepro remove "$DISTRIBUTION" "$PKG_NAME"
    fi
fi

# Add package to repository
print_info "Adding package to repository..."

if reprepro includedeb "$DISTRIBUTION" "$PACKAGE_FILE"; then
    print_success "Package $PKG_NAME-$PKG_VERSION added to $DISTRIBUTION successfully!"

    # Update repository metadata
    print_info "Updating repository metadata..."
    reprepro export "$DISTRIBUTION"

    print_success "Repository updated successfully!"

    echo ""
    echo "Package location in pool: pool/main/${PKG_NAME:0:1}/$PKG_NAME/"
    echo ""
    echo "To use this repository, add the following to /etc/apt/sources.list:"
    echo "  deb [arch=$ARCHITECTURE] http://your-repo-url/ $DISTRIBUTION main"

else
    print_error "Failed to add package to repository"
    exit 1
fi