#!/bin/sh
# Install an APKBUILD via Pacstall, converting to a temporary pacscript only
# when there is no committed/generated pacscript next to it.
set -eu

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

[ $# -eq 1 ] || { echo "usage: $0 pkgname-or-path" >&2; exit 1; }
target=$1

if [ -f "$target" ]; then
	apkbuild=$target
elif [ -f "$target/APKBUILD" ]; then
	apkbuild=$target/APKBUILD
else
	FPKGS_ROOT=$ROOT
	export FPKGS_ROOT
	apkbuild=$(resolve_recipe "$target") || { echo "no APKBUILD for $target" >&2; exit 1; }
fi

pkgdir=$(dirname "$apkbuild")
base=$(basename "$pkgdir")
if [ -f "$pkgdir/$base.pacscript" ]; then
	exec pacstall -P -I "$pkgdir/$base.pacscript"
fi
mkdir -p "$ROOT/.generated"
tmp="$ROOT/.generated/$base.pacscript"
trap 'rm -f "$tmp"' EXIT
if [ -f "$pkgdir/PKGBUILD" ]; then
	cp "$pkgdir/PKGBUILD" "$tmp"
	exec pacstall -P -I "$tmp"
fi

"$SELF_DIR/apkbuild-to-pacscript.sh" "$apkbuild" >"$tmp"
pacstall -P -I "$tmp"
