#!/usr/bin/env bash
# Build an Arch .pkg.tar.zst with makepkg. The package is not installed and
# it is not published.
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
if ! command -v makepkg >/dev/null 2>&1; then
  echo "makepkg is not installed. The Arch package job runs on archlinux/archlinux:base-devel." >&2
  exit 1
fi

version="$(bash "$root/scripts/ci/package-version.sh")"
export REPO_ROOT="$root"
export PAPERDOLL_PKGVER="$version"
export CARGO_HOME="${CARGO_HOME:-$root/cargo-home}"

work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
cp "$root/packaging/arch/PKGBUILD" "$work/PKGBUILD"

run_makepkg() {
  (cd "$work" && makepkg -f --noconfirm --nodeps)
}

if [[ "$(id -u)" -eq 0 ]]; then
  if ! id builduser >/dev/null 2>&1; then
    useradd -m builduser
  fi
  chown -R builduser:builduser "$root" "$work"
  su builduser -c "export REPO_ROOT='$root' PAPERDOLL_PKGVER='$version' CARGO_HOME='$CARGO_HOME' PATH='$PATH'; cd '$work' && makepkg -f --noconfirm --nodeps"
else
  run_makepkg
fi

mapfile -t packages < <(find "$work" -maxdepth 1 -type f -name "paperdoll-renderer-${version}-*-x86_64.pkg.tar.zst" ! -name '*.sig')
if [[ "${#packages[@]}" -ne 1 ]]; then
  echo "expected one Arch package, found ${#packages[@]}" >&2
  exit 1
fi
mkdir -p "$root/dist"
cp -f "${packages[0]}" "$root/dist/paperdoll-renderer-x86_64.pkg.tar.zst"
echo "wrote dist/paperdoll-renderer-x86_64.pkg.tar.zst"
