#!/bin/bash
# Debian changelog creation script with validation rules
set -e

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

# Function to extract version from CHANGELOG.md
extract_changelog_version() {
    local changelog_file="$PROJECT_ROOT/CHANGELOG.md"
    if [[ ! -f "$changelog_file" ]]; then
        echo "Error: CHANGELOG.md not found" >&2
        exit 1
    fi

    # Extract the first version number after "## [" pattern (excluding "Unreleased")
    grep -E "^## \[[0-9]+\." "$changelog_file" | head -1 | sed -E 's/^## \[([^]]+)\].*/\1/'
}

# Function to extract version from debian/changelog
extract_debian_changelog_version() {
    local debian_changelog="$PROJECT_ROOT/debian/changelog"
    if [[ ! -f "$debian_changelog" ]]; then
        echo ""  # Return empty if no debian changelog exists
        return
    fi

    # Extract version from first line: ekfsm (1.10.0-1) stable; urgency=medium
    grep -E "^ekfsm \(" "$debian_changelog" | head -1 | sed -E 's/^ekfsm \(([^-]+).*/\1/'
}

# Function to check if running in CI
is_ci_environment() {
    [[ -n "$CI" ]]
}

# Function to check if on release or main branch
is_release_or_main_branch() {
    [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]] || [[ "$CI_COMMIT_BRANCH" =~ ^release/ ]]
}

# Function to create automated debian changelog entry
create_automated_changelog() {
    local version="$1"
    local debian_revision="$2"
    local timestamp="$3"
    local debian_changelog="$PROJECT_ROOT/debian/changelog"

    # Create automated entry
    cat > "$debian_changelog" << EOF
ekfsm ($version-$debian_revision) stable; urgency=medium

  * Automated build from development environment
  * WARNING: This changelog entry is auto-generated and should not be committed
  * Please update debian/changelog manually with proper release notes
  * Single-artifact deployment with bundled dependencies
  * High compression packaging for minimal size

 -- Jan Jansen <jan@ekf.de>  $timestamp
EOF

    echo "⚠️  WARNING: Automated debian/changelog created. DO NOT COMMIT this version!" >&2
    echo "⚠️  Please update debian/changelog manually with proper release notes before committing." >&2
}

# Function to validate changelog versions match
validate_changelog_versions() {
    local changelog_version="$1"
    local debian_version="$2"

    if [[ "$changelog_version" != "$debian_version" ]]; then
        echo "❌ ERROR: Version mismatch detected!" >&2
        echo "   CHANGELOG.md version: $changelog_version" >&2
        echo "   debian/changelog version: $debian_version" >&2
        echo "   Please update debian/changelog to match CHANGELOG.md version" >&2
        exit 1
    fi

    echo "✅ Version validation passed: $changelog_version"
}

# Main execution
main() {
    echo "🔍 Validating debian changelog..."

    # Get 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 2>/dev/null || echo "0.0.0")
    fi

    TIMESTAMP=$(date -R)

    # Extract versions from both changelogs
    CHANGELOG_VERSION=$(extract_changelog_version)
    DEBIAN_VERSION=$(extract_debian_changelog_version)

    echo "📋 Current build version: $CURRENT_VERSION"
    echo "📋 CHANGELOG.md version: $CHANGELOG_VERSION"
    echo "📋 debian/changelog version: $DEBIAN_VERSION"

    if is_ci_environment && is_release_or_main_branch; then
        echo "🏗️  Running in CI on release/main branch - validating versions..."

        # In CI on release/main branch: validate versions match
        if [[ -z "$DEBIAN_VERSION" ]]; then
            echo "❌ ERROR: No debian/changelog found on release/main branch" >&2
            echo "   Please create debian/changelog manually with version $CHANGELOG_VERSION" >&2
            exit 1
        fi

        validate_changelog_versions "$CHANGELOG_VERSION" "$DEBIAN_VERSION"
        echo "✅ Validation successful - versions match"

    else
        # Local environment or non-release branch: create automated changelog with warning
        echo "🔧 Running locally or on non-release branch - creating automated changelog..."
        create_automated_changelog "$CURRENT_VERSION" "$DEBIAN_REVISION" "$TIMESTAMP"
    fi
}

# Execute main function
main "$@"
