#!/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.dsc>

Add a Debian source package to the EveBox repository.

OPTIONS:
    -d, --distribution <dist>  Distribution (stable or unstable) [default: unstable]
    -f, --force                Force addition even if package already exists
    -h, --help                 Display this help message

EXAMPLES:
    $0 evebox_0.18.0.dsc
    $0 --distribution stable evebox_0.18.0.dsc
    $0 -d unstable -f evebox_0.18.0.dsc

Note: The .dsc file and associated source files (.tar.gz, .tar.xz, etc.) must be
      in the same directory.

EOF
    exit 1
}

# Default values
DISTRIBUTION="unstable"
FORCE=false
DSC_FILE=""

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

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

# Check if DSC file exists
if [ ! -f "$DSC_FILE" ]; then
    print_error "DSC file not found: $DSC_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 from DSC file
print_info "Extracting package information..."
PKG_NAME=$(grep "^Source:" "$DSC_FILE" | awk '{print $2}')
PKG_VERSION=$(grep "^Version:" "$DSC_FILE" | awk '{print $2}')

if [ -z "$PKG_NAME" ] || [ -z "$PKG_VERSION" ]; then
    print_error "Failed to extract package information from $DSC_FILE"
    exit 1
fi

print_info "Source Package: $PKG_NAME"
print_info "Version: $PKG_VERSION"
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 removesrc "$DISTRIBUTION" "$PKG_NAME"
    fi
fi

# Get the directory of the DSC file
DSC_DIR=$(dirname "$DSC_FILE")

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

if reprepro -b . includedsc "$DISTRIBUTION" "$DSC_FILE"; then
    print_success "Source 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 "Source package location in pool: pool/main/${PKG_NAME:0:1}/$PKG_NAME/"
    echo ""
    echo "To use source packages from this repository, add the following to /etc/apt/sources.list:"
    echo "  deb-src https://your-repo-url/ $DISTRIBUTION main"

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