#!/bin/bash
# Full Debian package build script for systems with debhelper
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "Building Debian package with system tools..."

# Check if we have the necessary tools
if ! command -v dpkg-buildpackage >/dev/null 2>&1; then
    echo "Error: dpkg-buildpackage not found. Install with:"
    echo "  sudo apt-get install build-essential devscripts debhelper"
    exit 1
fi

# Ensure we have uv or pip
if ! command -v uv >/dev/null 2>&1; then
    echo "Warning: uv not found. Installing uv..."
    curl -LsSf https://astral.sh/uv/install.sh | sh
    export PATH="$HOME/.local/bin:$PATH"
    #source "$HOME/.local/bin/env"
fi

# Get debian revision
# Generate dynamic Debian revision
if [ -n "${GitVersion_CommitsSinceVersionSource}" ] && [ "${GitVersion_CommitsSinceVersionSource}" != "0" ]; then
    DEBIAN_REVISION="${GitVersion_CommitsSinceVersionSource}"
elif [ -n "${GitVersion_BuildMetaData}" ]; then
    DEBIAN_REVISION="${GitVersion_BuildMetaData}"
else
    DEBIAN_REVISION="${CI_PIPELINE_ID:-1}"
fi

# Get current version
if [ -n "$CI" ] && [ -n "${GitVersion_SemVer}" ]; then
    CURRENT_VERSION=${GitVersion_SemVer:-0.0.0}
else
    CURRENT_VERSION=$(uvx dunamai from any --no-metadata --style semver)
fi

echo "Building version: $CURRENT_VERSION"

# Update pyproject.toml version
uvx --from=toml-cli toml set --toml-path=pyproject.toml project.version "$CURRENT_VERSION"
echo "Updated pyproject.toml version to $CURRENT_VERSION"

"$SCRIPT_DIR/bundle-dependencies.sh"

# Validate and create/check debian changelog
"$SCRIPT_DIR/validate-debian-changelog.sh"

echo "Debian changelog validation completed"

# Clean previous builds
rm -rf debian/ekfsm/ || true
rm -f ../ekfsm_*.deb ../ekfsm_*.changes ../ekfsm_*.buildinfo || true

# Build the package
echo "Building package..."
dpkg-buildpackage -us -uc -b

# Move artifacts
mkdir -p dist
mv ../ekfsm_*.deb dist/
mv ../ekfsm_*.changes dist/ || true
mv ../ekfsm_*.buildinfo dist/ || true

echo ""
echo "✅ Debian package built successfully!"
echo ""
echo "Package information:"
ls -la dist/
echo ""
dpkg-deb -I dist/ekfsm_*.deb
echo ""
echo "Package size:"
du -h dist/ekfsm_*.deb
echo ""
echo "Installation command:"
echo "  sudo dpkg -i dist/ekfsm_${CURRENT_VERSION}-${DEBIAN_REVISION}_all.deb"
