#!/bin/sh
# build.sh - runs an APKBUILD recipe and drops the result into a destination
# folder. POSIX sh only. See functions.sh for the derivation notes (forked
# from alpinelinux/abuild, generic parts only).
#
# Usage: build.sh [-f apk|tar.gz|deb] [-o DESTDIR] [-s SYSROOT] [-n NATIVE_ROOT] [-t CHOST] [-k] <pkgname-or-path>
#
# <pkgname-or-path> is either a bare package name (resolved via
# resolve_recipe against $FPKGS_ROOT) or a direct path to a recipe
# directory/APKBUILD.
#
# Placing the output in DESTDIR is this script's whole job - pushing it
# anywhere (a domain, a host) is left to a future CI layer.
#
# CBUILD/CHOST: CBUILD is always this machine (guess_triplet()); CHOST
# defaults to CBUILD and is overridden with -t/--host when cross-compiling.
# depends/makedepends_host (target-arch, link-only - e.g. libprotobuf) stage
# into SYSROOT and only ever contribute compiler/linker flags. makedepends/
# makedepends_build (native, must run during this build - e.g. protoc) stage
# into NATIVE_ROOT and go on PATH. When CBUILD == CHOST, NATIVE_ROOT and
# SYSROOT are the same directory, so non-cross recipes see no change.
set -e

SELF_DIR=$(cd "$(dirname "$0")" && pwd)
FPKGS_ROOT=$(cd "$SELF_DIR/.." && pwd)
export FPKGS_ROOT

. "$SELF_DIR/functions.sh"

DESTDIR="./dist"
SYSROOT="./sysroot"
NATIVE_ROOT_ARG=""
CHOST=""
FORMAT=${FPKGS_FORMAT:-}
KEEP_WORKDIR=0

usage() {
	cat <<EOF
usage: $0 [-f apk|tar.gz|deb] [-o DESTDIR] [-s SYSROOT] [-n NATIVE_ROOT] [-t CHOST] [-k] <pkgname-or-path>

  -f FORMAT       apk, tar.gz or opt-in deb; overrides FPKGS_FORMAT
  -o DESTDIR      destination root for packages (default: ./dist)
  -s SYSROOT      tar.gz only: target dependency staging root (default: ./sysroot)
  -n NATIVE_ROOT  tar.gz only: root makedepends/makedepends_build get extracted into
                  (default: same as SYSROOT unless -t/--host cross-compiles)
  -t CHOST        target triplet, when different from this machine (CBUILD)
  -k              keep the temp work dir after the build (debugging)
EOF
}

while getopts "f:o:s:n:t:kh" opt; do
	case "$opt" in
	f) FORMAT=$OPTARG ;;
	o) DESTDIR=$OPTARG ;;
	s) SYSROOT=$OPTARG; LEGACY_ROOT_REQUESTED=1 ;;
	n) NATIVE_ROOT_ARG=$OPTARG; LEGACY_ROOT_REQUESTED=1 ;;
	t) CHOST=$OPTARG ;;
	k) KEEP_WORKDIR=1 ;;
	h)
		usage
		exit 0
		;;
	*)
		usage
		exit 1
		;;
	esac
done
shift $((OPTIND - 1))

[ $# -eq 1 ] || {
	usage
	exit 1
}
target="$1"

FPKGS_FORMAT=$FORMAT
FORMAT=$(package_format)
FPKGS_FORMAT=$FORMAT
export FPKGS_FORMAT
CBUILD=$(guess_triplet)
CHOST="${CHOST:-$(default_target "$FORMAT")}"

if [ "$FORMAT" = deb ]; then
	[ "${LEGACY_ROOT_REQUESTED:-0}" -eq 0 ] || die '-s/-n are tar.gz-only staging options'
	if [ -f "$target" ]; then
		apkbuild=$target
	elif [ -f "$target/APKBUILD" ]; then
		apkbuild=$target/APKBUILD
	else
		apkbuild=$(resolve_recipe "$target") || die "no recipe found for '$target'"
	fi
	exec "$SELF_DIR/build-deb.sh" "$apkbuild" "$DESTDIR" "$CHOST" "$KEEP_WORKDIR"
fi

if [ "$FORMAT" = apk ]; then
	# A vendor spelling alone must not turn a native musl build into a cross build.
	case "$CBUILD" in
	*-unknown-linux-musl) [ "$CHOST" != "$(default_target apk)" ] || CBUILD=$CHOST ;;
	esac
	[ "${LEGACY_ROOT_REQUESTED:-0}" -eq 0 ] || die '-s/-n are tar.gz staging options; configure upstream CBUILDROOT/PATH for APK builds'
	if [ -f "$target" ]; then
		apkbuild=$target
	elif [ -f "$target/APKBUILD" ]; then
		apkbuild=$target/APKBUILD
	else
		apkbuild=$(resolve_recipe "$target") || die "no recipe found for '$target'"
	fi
	export CBUILD CHOST
	exec "$SELF_DIR/build-apk.sh" "$apkbuild" "$DESTDIR" "$CHOST" "$KEEP_WORKDIR"
fi

mkdir -p "$DESTDIR" "$SYSROOT"
DESTDIR=$(cd "$DESTDIR" && pwd)
SYSROOT=$(cd "$SYSROOT" && pwd)

if cross_compiling; then
	NATIVE_ROOT="${NATIVE_ROOT_ARG:-./native-root}"
	mkdir -p "$NATIVE_ROOT"
	NATIVE_ROOT=$(cd "$NATIVE_ROOT" && pwd)
else
	NATIVE_ROOT="$SYSROOT"
fi

# ---------------------------------------------------------------------------
# Locate the recipe
# ---------------------------------------------------------------------------

if [ -f "$target" ]; then
	apkbuild="$target"
elif [ -f "$target/APKBUILD" ]; then
	apkbuild="$target/APKBUILD"
else
	apkbuild=$(resolve_recipe "$target") || die "no recipe found for '$target' (searched $(canonical_os)/, Unix/, noarch/, any/ under $FPKGS_ROOT)"
fi

recipe_dir=$(cd "$(dirname "$apkbuild")" && pwd)
msg "using recipe: $apkbuild"

# ---------------------------------------------------------------------------
# Work dirs
# ---------------------------------------------------------------------------

# TMPDIR is the POSIX convention; busybox-w32 (this project's primary
# Windows shell) sets TEMP/TMP instead and has no /tmp at all.
_tmproot="${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"
workdir=$(mktemp -d "$_tmproot/fpkgs-build.XXXXXX")
srcdir="$workdir/src"
pkgdir="$workdir/pkg"
mkdir -p "$srcdir" "$pkgdir"

cleanup() {
	if [ "$KEEP_WORKDIR" -eq 1 ]; then
		msg "keeping work dir: $workdir"
	else
		rm -rf "$workdir"
	fi
}
trap cleanup EXIT

builddir="$srcdir"

# ---------------------------------------------------------------------------
# Load the recipe. APKBUILD is POSIX per Alpine policy, so it's sourced
# directly - no bash shim needed (PKGBUILD compatibility is handled entirely
# by the separate, one-time pkgbuild-to-apkbuild.sh conversion instead).
# ---------------------------------------------------------------------------

pkgrel=0
# shellcheck disable=SC1090
. "$apkbuild"

: "${pkgname:?APKBUILD did not set pkgname}"
: "${pkgver:?APKBUILD did not set pkgver}"

# A recipe may set its own builddir= (e.g. Linux/td/APKBUILD's
# builddir="$srcdir/"), which took effect when it was sourced above and
# simply overrides the $srcdir default already assigned before that.

# ---------------------------------------------------------------------------
# Dependency resolution against the sysroot (replaces abuild's apk-based
# `deps()`, which installs onto the live OS - not appropriate here).
# ---------------------------------------------------------------------------

# resolve_and_stage_dep DEP ROOT - stage a single dependency's built tarball
# into ROOT (either $NATIVE_ROOT or $SYSROOT, depending on which list it
# came from - see the two loops below).
resolve_and_stage_dep() {
	_dep="$1"
	_root="$2"
	_dep_apkbuild=$(resolve_recipe "$_dep") || {
		warning "no recipe for dependency '$_dep' - assuming it's a host tool, not staging it"
		return 0
	}

	# is this dependency a *verify-only* recipe (build-essentials-stub style)?
	if grep -Eq '^verify[[:space:]]*\(\)' "$_dep_apkbuild" 2>/dev/null; then
		run_verify_recipe "$_dep_apkbuild" || die "dependency check failed for '$_dep'"
		return 0
	fi

	_dep_tarball=""
	for _archdir in "$CHOST" noarch; do
		_candidate=$(ls "$DESTDIR/$_archdir/${_dep}"-*.tar.gz 2>/dev/null | head -n1)
		[ -n "$_candidate" ] && {
			_dep_tarball="$_candidate"
			break
		}
	done

	if [ -z "$_dep_tarball" ]; then
		warning "dependency '$_dep' has a recipe but no built tarball in $DESTDIR yet - build it first with: $0 -o $DESTDIR -s $SYSROOT $_dep"
		return 0
	fi

	msg "staging dependency '$_dep' into $_root: $_dep_tarball"
	mkdir -p "$_root"
	tar -xzf "$_dep_tarball" -C "$_root"
}

run_verify_recipe() {
	_verify_apkbuild="$1"
	# shellcheck disable=SC1090
	(
		. "$_verify_apkbuild"
		verify
	)
}

# SYSROOT (CHOST, link-only) only ever contributes compiler/linker flags -
# its binaries generally can't execute on CBUILD once cross-compiling, so it
# must never go on PATH. NATIVE_ROOT (CBUILD, executable) is what goes on
# PATH; when not cross-compiling the two are the same directory anyway.
sysroot_env() {
	export CFLAGS="-I$SYSROOT/usr/include ${CFLAGS:-}"
	export CPPFLAGS="-I$SYSROOT/usr/include ${CPPFLAGS:-}"
	export LDFLAGS="-L$SYSROOT/usr/lib ${LDFLAGS:-}"
	export PKG_CONFIG_PATH="$SYSROOT/usr/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
	export PATH="$NATIVE_ROOT/usr/bin:$PATH"
}

# Plain `makedepends` (no _build/_host split - every current recipe) is
# treated as makedepends_build, matching abuild's own fallback for the
# non-cross case: it's the only list group and CBUILD == CHOST already makes
# NATIVE_ROOT == SYSROOT, so behavior is unchanged for e.g. kcgi.
for _dep in ${makedepends:-} ${makedepends_build:-}; do
	resolve_and_stage_dep "$_dep" "$NATIVE_ROOT"
done

for _dep in ${depends:-} ${makedepends_host:-}; do
	resolve_and_stage_dep "$_dep" "$SYSROOT"
done

sysroot_env
if [ "${FPKGS_REPRODUCIBLE:-0}" = 1 ]; then
	# Debian's immutable version archive must not embed randomized build paths.
	export CFLAGS="${CFLAGS:-} -ffile-prefix-map=$workdir=."
	export CXXFLAGS="${CXXFLAGS:-} -ffile-prefix-map=$workdir=."
fi

# ---------------------------------------------------------------------------
# If this recipe itself is verify()-only (e.g. build-essentials-stub), run
# that and stop - nothing to fetch/build/package.
# ---------------------------------------------------------------------------

# APKBUILDs only ever define functions by being sourced (never add a `verify`
# binary to PATH), so a successful `command -v verify` here reliably means
# the recipe defined verify().
if command -v verify >/dev/null 2>&1; then
	msg "running verify() for $pkgname"
	verify
	msg "$pkgname: all checks passed"
	exit 0
fi

# ---------------------------------------------------------------------------
# Normal recipe: fetch -> unpack -> prepare -> build -> package -> output
# ---------------------------------------------------------------------------

msg "fetching sources for $pkgname-$pkgver"
default_fetch

msg "unpacking sources"
for _src in ${source:-}; do
	_fname=$(filename_from_uri "$_src")
	default_unpack "$srcdir/$_fname" "$srcdir"
done

default_prepare

# builddir defaults to $srcdir (recipes cd into their own extracted subdir
# from build()/package(), matching Linux/td's and Linux/otpw's existing
# convention) unless the recipe set its own builddir= when sourced above.

msg "building $pkgname-$pkgver"
(cd "$builddir" && build)

msg "packaging $pkgname-$pkgver"
(cd "$builddir" && package)

# archdir is keyed on CHOST (what this build targets), not CBUILD (the
# machine running it) - a cross-build's output has to be findable by the
# triplet it's *for*. `any`/`noarch` (Arch/Alpine's names for the same thing)
# mean genuinely arch-independent - one build serves every arch. `all` is a
# *different* Alpine meaning that's easy to conflate with those two: it means
# "arch-specific, build once per supported arch" (e.g. kcgi, otpw, td all
# compile native code) - that still needs a real per-triplet directory, not
# noarch, or every arch's build silently clobbers the same noarch/ slot.
archdir="noarch"
case "${arch:-}" in
any | noarch) archdir="noarch" ;;
*) archdir="$CHOST" ;;
esac

# ---------------------------------------------------------------------------
# Subpackage splitting: subpackages="dev doc" runs default_dev()/default_doc()
# (or the recipe's own dev()/doc() override) over $pkgdir into a fresh
# subpkgdir, each producing its own tarball. This has to run *before* the
# base package_output below - splitting moves matched files out of $pkgdir,
# so the base tarball only reflects what's left once it runs after this.
# ---------------------------------------------------------------------------

for _suffix in ${subpackages:-}; do
	subpkgdir="$workdir/subpkg-$_suffix"
	mkdir -p "$subpkgdir"

	if command -v "$_suffix" >/dev/null 2>&1; then
		_splitfn="$_suffix"
	elif command -v "default_$_suffix" >/dev/null 2>&1; then
		_splitfn="default_$_suffix"
	else
		warning "no split function for subpackage suffix '$_suffix' - skipping"
		continue
	fi

	msg "splitting subpackage: $pkgname-$_suffix"
	# Real abuild's pre_split() cd's to $pkgdir before running the split
	# function - its default_* bodies rely on that cwd for their own bare
	# glob patterns (e.g. `amove usr/lib/*.so.[0-9]*`) to expand correctly.
	(cd "$pkgdir" && "$_splitfn")

	if [ -z "$(ls -A "$subpkgdir" 2>/dev/null)" ]; then
		warning "subpackage '$_suffix' matched no files - skipping empty tarball"
		continue
	fi

	subout=$(package_output "$archdir" "$subpkgdir" "-$_suffix")
	msg "wrote $subout"
	[ -f "$subout.sha256" ] && msg "wrote $subout.sha256"
done

out=$(package_output "$archdir")
msg "wrote $out"
[ -f "$out.sha256" ] && msg "wrote $out.sha256"
