#!/usr/bin/env bash
# Pack usr/ from an Arch .pkg.tar.zst into posprint-<ver>-x86_64.tar.gz for AUR posprint-bin.
#
# Usage:
#   make-linux-bin-tarball.sh [posprint-*.pkg.tar.zst ...] [out.tar.gz] [version]
#
# Extra .pkg.tar.zst arguments (e.g. a shell glob that also matches the debug
# split package) are ignored; only the non-debug package is used. The tarball is
# never written over a package path.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"

is_debug_pkg() {
  local base
  base="$(basename -- "$1")"
  # Arch debug split packages: posprint-debug-<ver>-<rel>-<arch>.pkg.tar.zst
  [[ "$base" == posprint-debug-* || "$base" == *-debug-*.pkg.tar.zst ]]
}

is_pkg() {
  [[ "$1" == *.pkg.tar.zst || "$1" == *.pkg.tar ]]
}

is_tarball_out() {
  [[ "$1" == *.tar.gz ]]
}

looks_like_version() {
  [[ "$1" =~ ^v?[0-9]+\.[0-9]+ ]]
}

PKG_CANDIDATES=()
OUT=""
VERSION=""
UNKNOWN=()

for arg in "$@"; do
  if is_pkg "$arg"; then
    PKG_CANDIDATES+=("$arg")
  elif is_tarball_out "$arg"; then
    if [[ -n "$OUT" ]]; then
      echo "Multiple output paths: $OUT and $arg" >&2
      exit 1
    fi
    OUT="$arg"
  elif looks_like_version "$arg"; then
    VERSION="$arg"
  else
    UNKNOWN+=("$arg")
  fi
done

if [[ ${#UNKNOWN[@]} -gt 0 ]]; then
  echo "Unexpected arguments: ${UNKNOWN[*]}" >&2
  echo "Usage: $0 [posprint-*.pkg.tar.zst ...] [out.tar.gz] [version]" >&2
  exit 1
fi

if [[ ${#PKG_CANDIDATES[@]} -eq 0 ]]; then
  shopt -s nullglob
  PKG_CANDIDATES=("$ROOT"/packaging/arch/posprint-*.pkg.tar.zst "$ROOT"/dist/posprint-*.pkg.tar.zst)
  shopt -u nullglob
fi

PKG_ZST=""
for candidate in "${PKG_CANDIDATES[@]+"${PKG_CANDIDATES[@]}"}"; do
  if ! is_debug_pkg "$candidate"; then
    PKG_ZST="$candidate"
    break
  fi
done

if [[ -z "$PKG_ZST" ]]; then
  echo "Usage: $0 <posprint-*.pkg.tar.zst> [out.tar.gz] [version]" >&2
  echo "No non-debug Arch package found." >&2
  exit 1
fi

if [[ ! -f "$PKG_ZST" ]]; then
  echo "Package not found: $PKG_ZST" >&2
  exit 1
fi

if [[ -z "$VERSION" ]]; then
  VERSION="$(grep '^version = ' "$ROOT/Cargo.toml" | sed -E 's/.*"([^"]+)"/\1/')"
fi
VERSION="${VERSION#v}"

if [[ -z "$OUT" ]]; then
  mkdir -p "$ROOT/dist"
  OUT="$ROOT/dist/posprint-${VERSION}-x86_64.tar.gz"
fi

if is_pkg "$OUT"; then
  echo "Refusing to write tarball over package path: $OUT" >&2
  exit 1
fi

EXTRACT="$(mktemp -d)"
cleanup() { rm -rf "$EXTRACT"; }
trap cleanup EXIT

if command -v bsdtar >/dev/null; then
  bsdtar -C "$EXTRACT" -xf "$PKG_ZST"
else
  tar -C "$EXTRACT" -xf "$PKG_ZST"
fi

if [[ ! -d "$EXTRACT/usr" ]]; then
  echo "Arch package did not contain usr/: $PKG_ZST" >&2
  exit 1
fi

mkdir -p "$(dirname "$OUT")"
tar -C "$EXTRACT" -czf "$OUT" usr
if [[ ! -s "$OUT" ]]; then
  echo "Failed to write tarball: $OUT" >&2
  exit 1
fi
echo "Wrote $OUT from $PKG_ZST"
