#!/bin/bash
set -euo pipefail

PACKAGE="rust-hwlib"
orig_tar=$(ls -t ../${PACKAGE}_*.orig.tar.gz | head -n1)

if [[ ! -f "$orig_tar" ]]; then
  echo "No orig tarball found."
  exit 1
fi

version=$(basename "$orig_tar" | sed -E "s/${PACKAGE}_([0-9\.]+)(\+[^_]*)?\.orig\.tar\.gz/\1/")
tmpdir=$(mktemp -d)
trap "rm -rf \"$tmpdir\"" EXIT

tar -xf "$orig_tar" -C "$tmpdir"
toplevel=$(find "$tmpdir" -mindepth 1 -maxdepth 1 -type d)

if [[ -d "$toplevel/client" ]]; then
  mv "$toplevel/client/"* "$toplevel/"
  rmdir "$toplevel/client"
fi

new_tarball="../${PACKAGE}_${version}+us.orig.tar.gz"
tar -czf "$new_tarball" -C "$tmpdir" "$(basename "$toplevel")"
echo "Repacked to $new_tarball"
