#!/bin/bash -ex

# SPDX-FileCopyrightText: 2023 Debian Rust Maintainers
# SPDX-License-Identifier: MIT

TMPDIR="$(mktemp -d)"
TMPDIR2="$(mktemp -d)"
CURDIR="$PWD"

cleanup() {
    rm -rf "$TMPDIR" "$TMPDIR2"
}

trap cleanup EXIT ERR

mkdir -p "$TMPDIR"/src "$TMPDIR"/manifest
cp -raT "$CURDIR" "$TMPDIR"/src
cp -r "$CURDIR"/debian "$TMPDIR"/manifest
sed -i "s|crate_src_path = .*|crate_src_path = \"../../src\"|" "$TMPDIR"/manifest/debian/debcargo.toml
cd "$TMPDIR"/src
dh_quilt_patch
"$CURDIR"/debian/flatten-local-crates.py .
rm -v "$TMPDIR"/manifest/debian/{control,patches/series}
rm -rf "$TMPDIR"/src/debian "$TMPDIR"/src/.pc
cd "$TMPDIR"
rm -rf "$TMPDIR2"
debcargo package --config "$TMPDIR"/manifest/debian/debcargo.toml --directory "$TMPDIR2" rustup
# some very simple fix-ups
rm -fv "$TMPDIR2"/debian/compat
sed -i 's|Source: rust-rustup|Source: rustup|' "$TMPDIR2"/debian/control
sed -i 's|crate_src_path = .*|crate_src_path = "."|' "$TMPDIR2"/debian/debcargo.toml
# end of fix-ups
cp -r "$TMPDIR2"/debian "$CURDIR"
