#!/bin/sh
# Internal APK backend. Upstream abuild owns every recipe/packaging phase.
set -eu
SELF_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
. "$SELF_DIR/functions.sh"
recipe=$1
dest=$2
target=$3
keep=$4
abuild=${FPKGS_ABUILD:-abuild}
command -v "$abuild" >/dev/null 2>&1 || die 'upstream abuild is required; install the bootstrap .debs or select -f tar.gz'
recipe_dir=$(CDPATH= cd -- "$(dirname "$recipe")" && pwd)
repo=$(basename "$(dirname "$recipe_dir")")
pkg=$(basename "$recipe_dir")
mkdir -p "$dest"
dest=$(CDPATH= cd -- "$dest" && pwd)
work=$(mktemp -d "${TMPDIR:-/tmp}/fpkgs-apk.XXXXXX")
cleanup() {
	if [ "$keep" -eq 1 ]; then msg "keeping work dir: $work"; else rm -rf "$work"; fi
}
trap cleanup EXIT
trap 'exit 1' HUP INT TERM
mkdir -p "$work/recipes/$repo/$pkg"
cp -R "$recipe_dir/." "$work/recipes/$repo/$pkg/"
# Build in a fresh copy: no mutation of the checkout or reuse of stale APKs.
(
	cd "$work/recipes/$repo/$pkg"
	# minci exports its own staging paths. Never let abuild clean those directories.
	unset srcdir pkgdir subpkgdir tmpdir startdir builddir pkgbasedir workdir destdir
	APKBUILD="$work/recipes/$repo/$pkg/$(basename "$recipe")" \
		REPODEST="$work/packages" SRCDEST="${SRCDEST:-$work/sources}" "$abuild" -d
)
[ -d "$work/packages" ] || die 'abuild produced no repository'
find "$work/packages" -type f -name '*.apk' >"$work/apks"
[ -s "$work/apks" ] || die 'abuild produced no APKs'
# Preserve upstream repository/architecture layout and the signed index.
find "$work/packages" -type f \( -name '*.apk' -o -name 'APKINDEX.tar.gz' \) >"$work/artifacts"
while IFS= read -r file; do
	if command -v sha256sum >/dev/null 2>&1; then
		digest=$(sha256sum "$file" | awk '{print $1}')
	else
		digest=$(shasum -a 256 "$file" | awk '{print $1}')
	fi
	printf '%s\n' "$digest" >"$file.sha256"
done <"$work/artifacts"
mkdir -p "$dest/$target"
cp -R "$work/packages/." "$dest/$target/"
msg "wrote APK repository to $dest/$target/$repo"
