#!/bin/bash
set -e

if [ $# -ne 1 ]; then
    echo "Usage: $0 <version>"
    echo "Example: $0 0.7.0"
    echo ""
    echo "Use 'uscan' to check for new upstream versions first."
    exit 1
fi

VERSION="$1"
SCRIPT_DIR="$(dirname "$(realpath "$0")")"
TARGET="$(dirname "$(dirname "$SCRIPT_DIR")")"
WORKDIR="$TARGET/coreutils-repack"

echo "Repacking coreutils version $VERSION"
echo "Target directory: $TARGET"
echo "Work directory: $WORKDIR"

# Check if running interactively
if [ -t 0 ]; then
    echo "Please update the version in debian/changelog"
    read -p "Press enter when done..."
else
    echo "Running non-interactively - assuming changelog is up to date"
fi

# Clone tagged source first
echo "Cloning coreutils source at version $VERSION..."
rm -rf "$WORKDIR"
if ! git clone git@github.com:uutils/coreutils.git -b "$VERSION" "$WORKDIR"; then
    echo "Error: Failed to clone coreutils at version $VERSION"
    exit 1
fi

# Clone l10n repo
echo "Cloning coreutils-l10n at version $VERSION..."
rm -rf /tmp/coreutils-l10n
if ! git clone https://github.com/uutils/coreutils-l10n.git -b "$VERSION" /tmp/coreutils-l10n; then
    echo "Warning: Failed to clone coreutils-l10n at version $VERSION, trying main branch..."
    if ! git clone https://github.com/uutils/coreutils-l10n.git /tmp/coreutils-l10n; then
        echo "Error: Failed to clone coreutils-l10n repo"
        exit 1
    fi
fi

cd "$WORKDIR"

# Add localized versions (only locale files, not overwriting structure)
echo "Adding localized files..."
if [ -d "/tmp/coreutils-l10n/src/uu" ]; then
    for util_dir in /tmp/coreutils-l10n/src/uu/*/; do
        util_name=$(basename "$util_dir")
        if [ -d "./src/uu/$util_name" ]; then
            cp -R "$util_dir"* "./src/uu/$util_name/" 2>/dev/null || true
        fi
    done
fi
if [ -d "/tmp/coreutils-l10n/src/uucore" ]; then
    cp -R /tmp/coreutils-l10n/src/uucore/* ./src/uucore/ 2>/dev/null || true
fi

# Download tldr pages
echo "Downloading tldr pages..."
mkdir -p docs
if ! curl -L https://github.com/tldr-pages/tldr/releases/latest/download/tldr.zip -o docs/tldr.zip; then
    echo "Warning: Failed to download tldr.zip, continuing without it"
    rm -f docs/tldr.zip
fi

# Vendor dependencies
echo "Vendoring Cargo dependencies..."
if ! cargo vendor; then
    echo "Error: Failed to vendor cargo dependencies"
    exit 1
fi

# Copy debian directory to build directory
echo "Copying debian directory to build directory..."
if ! cp -R "$SCRIPT_DIR" "$WORKDIR/debian"; then
    echo "Error: Failed to copy debian directory"
    exit 1
fi

# Clean up
rm -rf "$WORKDIR/.pc/"

# Force clean before creating tarball
echo "Running debian/rules clean..."
debian/rules clean || true

# Remove problematic symlinks that point outside the source tree
echo "Removing problematic symlinks..."
find "$WORKDIR/debian/cargo_registry" -type l -delete 2>/dev/null || true

cd "$TARGET"

# Remove any pre-existing orig tarballs for this version to avoid
# dpkg-source complaining about multiple orig.tar files (e.g. .gz and .xz).
echo "Removing any pre-existing orig tarballs for version $VERSION..."
rm -f "rust-coreutils_${VERSION}.orig.tar."{gz,bz2,xz,lzma}

# Strip .git metadata so gbp import-orig accepts the tarball.
echo "Removing .git metadata from source tree..."
find "$WORKDIR" -depth -name .git -exec rm -rf {} +

echo "Creating source tarball..."
if ! tar Jcvf "rust-coreutils_${VERSION}.orig.tar.xz" coreutils-repack/; then
    echo "Error: Failed to create source tarball"
    exit 1
fi

echo "Building source package..."
if ! dpkg-source -b -i coreutils-repack; then
    echo "dpkg-source failed - attempting to rebase patches automatically..."
    cd "$WORKDIR"

    # Remove any partially applied patches
    QUILT_PATCHES=debian/patches quilt pop -a 2>/dev/null || true

    # Get list of all patches
    total_patches=$(QUILT_PATCHES=debian/patches quilt series | wc -l)
    echo "Found $total_patches patches to rebase"

    # Apply and refresh each patch individually
    patch_count=0
    failed_patches=0

    # Try to apply as many patches as possible
    while QUILT_PATCHES=debian/patches quilt push -f 2>/dev/null; do
        patch_count=$((patch_count + 1))
        current_patch=$(QUILT_PATCHES=debian/patches quilt top)
        echo "Applied patch: $current_patch"

        # Try to refresh it
        if QUILT_PATCHES=debian/patches quilt refresh; then
            echo "✓ Successfully refreshed $current_patch"
        else
            echo "⚠ Warning: Failed to refresh $current_patch, but continuing..."
            failed_patches=$((failed_patches + 1))
        fi
    done

    echo "Patch rebase complete: $patch_count applied, $failed_patches failed"

    cd "$TARGET"
    echo "Retrying dpkg-source after patch rebase..."
    if ! dpkg-source -b -i coreutils-repack; then
        echo "Warning: dpkg-source still has issues but continuing..."
        echo "Some patches may need manual adjustment later."
        echo "Check patches in: $WORKDIR/debian/patches/"

        # Try to create a minimal source package by temporarily removing problematic patches
        cd "$WORKDIR"

        # Pop all patches and just apply the ones that worked
        QUILT_PATCHES=debian/patches quilt pop -a 2>/dev/null || true

        # Apply only the patches we know work
        for i in $(seq 1 $patch_count); do
            if ! QUILT_PATCHES=debian/patches quilt push 2>/dev/null; then
                break
            fi
        done

        cd "$TARGET"
        echo "Creating source package with partial patches applied..."
        if ! dpkg-source -b -i coreutils-repack; then
            echo "Error: Unable to create source package even with partial patches"
            echo "Manual intervention definitely required."
            exit 1
        fi
    fi
fi

echo ""
echo "✅ Repack complete!"
echo "Created: rust-coreutils_${VERSION}.orig.tar.xz"
echo "Created: rust-coreutils_${VERSION}-1.dsc"
echo "Created: rust-coreutils_${VERSION}-1.debian.tar.xz"

# Cleanup
rm -rf "$WORKDIR"
