# functions.sh - portable core, derived from alpinelinux/abuild's functions.sh.in
# and abuild.in, stripped of everything Alpine/apk-specific (live apk install,
# package signing, repo index generation, bwrap/fakeroot sandboxing). POSIX sh
# only - no bash arrays, no [[, no local -n.
#
# Sourced by build.sh; not meant to be run standalone.

STATUS_INFO=">"
STATUS_ERROR="!"
STATUS_OK="+"

msg() {
	printf '%s %s\n' "$STATUS_INFO" "$*" >&2
}

warning() {
	printf '%s WARNING: %s\n' "$STATUS_ERROR" "$*" >&2
}

error() {
	printf '%s %s\n' "$STATUS_ERROR" "$*" >&2
}

die() {
	error "$*"
	exit 1
}

# list_has NEEDLE HAYSTACK... - true if NEEDLE is one of the remaining args.
list_has() {
	needle="$1"
	shift
	for hay in "$@"; do
		[ "$hay" = "$needle" ] && return 0
	done
	return 1
}

# ---------------------------------------------------------------------------
# Triplet detection - uname only, deliberately no clang/rustc/config.guess
# dependency, so this also works wherever mor.sh/mor.cmd need to make the
# same decision to pick the right download.
# ---------------------------------------------------------------------------

# is_android - Android's kernel is Linux, so `uname -s` there is just "Linux"
# like any other box; it can't be told apart by uname -s/-m alone. ANDROID_ROOT/
# ANDROID_DATA are set in Android's own environment (including Termux);
# /system/build.prop is the classic filesystem marker for anything that
# doesn't inherit that environment (e.g. a plain chrooted userland).
is_android() {
	[ -n "${ANDROID_ROOT:-}" ] || [ -n "${ANDROID_DATA:-}" ] || [ -f /system/build.prop ]
}

guess_triplet() {
	_uname_s=$(uname -s)
	_uname_m=$(uname -m)

	case "$_uname_m" in
	arm64) _arch=aarch64 ;;
	amd64) _arch=x86_64 ;;
	i386 | i686) _arch=x86 ;;
	*) _arch=$_uname_m ;;
	esac

	# Checked ahead of the `Linux)` case below, which would otherwise always
	# win first (its pattern is a literal match on uname -s's actual value).
	# The Android NDK's own triples have no vendor field, and arm32 uses the
	# "androideabi" ABI suffix instead of a plain "android" one.
	if is_android; then
		case "$_uname_m" in
		armv7* | arm) echo "armv7a-linux-androideabi" ;;
		*) echo "${_arch}-linux-android" ;;
		esac
		return
	fi

	case "$_uname_s" in
	Darwin)
		echo "${_arch}-apple-darwin"
		;;
	Linux)
		if [ -f /etc/alpine-release ] || (ldd --version 2>&1 | grep -qi musl); then
			echo "${_arch}-unknown-linux-musl"
		else
			echo "${_arch}-unknown-linux-gnu"
		fi
		;;
	FreeBSD | OpenBSD | NetBSD)
		echo "${_arch}-unknown-$(echo "$_uname_s" | tr 'A-Z' 'a-z')"
		;;
	# Windows_NT is what busybox-w32's own uname.c hardcodes as sysname
	# (confirmed straight from its source) - this project's primary
	# supported Windows shell (mor.cmd's "extreme bootstrap" ethos: a
	# single busybox.exe, no MSYS2/Git-Bash/Cygwin required). MINGW*/
	# MSYS*/CYGWIN* are kept for whoever does have one of those installed,
	# but they're a secondary path, not what to design around.
	Windows_NT | MINGW* | MSYS* | CYGWIN*)
		echo "${_arch}-pc-windows-gnu"
		;;
	*)
		echo "${_arch}-unknown-$(echo "$_uname_s" | tr 'A-Z' 'a-z')"
		;;
	esac
}

# canonical_os - the uname -s bucket used for recipe resolution (distinct from
# guess_triplet's output-artifact naming; see resolve_recipe below).
canonical_os() {
	is_android && {
		echo "Android"
		return
	}
	_uname_s=$(uname -s)
	case "$_uname_s" in
	Windows_NT | MINGW* | MSYS* | CYGWIN*) echo "Windows" ;;
	*) echo "$_uname_s" ;;
	esac
}

# APK is the Linux default; the legacy archive backend remains explicit.
package_format() {
	_format=${FPKGS_FORMAT:-}
	if [ -z "$_format" ]; then
		case "$(canonical_os)" in
		Linux) _format=apk ;;
		*) _format=tar.gz ;;
		esac
	fi
	case "$_format" in
	apk | tar.gz | deb) printf '%s\n' "$_format" ;;
	*) die "unsupported package format: $_format (use apk, tar.gz or deb)" ;;
	esac
}

default_target() {
	_native=$(guess_triplet)
	case "$1:$_native" in
	apk:*-unknown-linux-gnu | apk:*-unknown-linux-musl)
		printf '%s-alpine-linux-musl\n' "${_native%%-*}" ;;
	*) printf '%s\n' "$_native" ;;
	esac
}

# ---------------------------------------------------------------------------
# Recipe resolution: <canonical-os>/ -> Unix/ (skipped on Windows) -> noarch/
# -> any/. Most-specific-first, matching e.g. Darwin/bmake beating Unix/bmake.
# ---------------------------------------------------------------------------

resolve_recipe() {
	_pkgname="$1"
	_os=$(canonical_os)

	for _bucket in "$_os" Unix noarch any; do
		[ "$_os" = "Windows" ] && [ "$_bucket" = "Unix" ] && continue
		_candidate="$FPKGS_ROOT/$_bucket/$_pkgname/APKBUILD"
		if [ -f "$_candidate" ]; then
			echo "$_candidate"
			return 0
		fi
	done

	return 1
}

# ---------------------------------------------------------------------------
# Source fetching / unpacking - derived from abuild's uri_fetch/default_fetch/
# default_unpack.
# ---------------------------------------------------------------------------

is_remote() {
	case "$1" in
	http://* | https://* | ftp://*) return 0 ;;
	*) return 1 ;;
	esac
}

filename_from_uri() {
	case "$1" in
	*::*) echo "${1%%::*}" ;;
	*) echo "${1##*/}" ;;
	esac
}

uri_fetch() {
	_url="$1"
	_dest="$2"
	if command -v curl >/dev/null 2>&1; then
		curl -fL -o "$_dest" "$_url"
	elif command -v wget >/dev/null 2>&1; then
		wget -O "$_dest" "$_url"
	else
		die "no curl or wget available to fetch $_url"
	fi
}

# extension_of URL - mirrors mor.sh's own extension case statement, reused
# here rather than reinvented.
extension_of() {
	case "$1" in
	*.tar.gz | *.tgz) echo ".tar.gz" ;;
	*.zip) echo ".zip" ;;
	*.tar) echo ".tar" ;;
	*.7z) echo ".7z" ;;
	*.bz2) echo ".bz2" ;;
	*.xz) echo ".xz" ;;
	*) echo "" ;;
	esac
}

default_unpack() {
	_archive="$1"
	_destdir="$2"
	_ext=$(extension_of "$_archive")
	case "$_ext" in
	.tar.gz | .tgz) tar -xzf "$_archive" -C "$_destdir" ;;
	.tar) tar -xf "$_archive" -C "$_destdir" ;;
	.bz2) tar -xjf "$_archive" -C "$_destdir" ;;
	.xz) tar -xJf "$_archive" -C "$_destdir" ;;
	.zip)
		if command -v unzip >/dev/null 2>&1; then
			unzip -q "$_archive" -d "$_destdir"
		else
			tar -xf "$_archive" -C "$_destdir"
		fi
		;;
	.7z) (cd "$_destdir" && 7z x "$_archive" -y >/dev/null) ;;
	*) : ;; # not an archive (e.g. a lone patch file) - nothing to unpack
	esac
}

# default_fetch: download every entry in $source into $srcdir. Local
# (non-URL) entries are copied from the recipe dir instead. Verifies
# sha512sums/sha256sums when the recipe defines one; warns and continues when
# absent (several existing recipes, e.g. kcgi's, don't define one).
default_fetch() {
	for _src in $source; do
		_fname=$(filename_from_uri "$_src")
		if is_remote "$_src"; then
			[ -f "$srcdir/$_fname" ] || uri_fetch "$_src" "$srcdir/$_fname"
		else
			cp "$recipe_dir/$_src" "$srcdir/$_fname"
		fi
	done

	_sums="${sha512sums:-${sha256sums:-}}"
	_algo=sha512sum
	[ -n "${sha256sums:-}" ] && [ -z "${sha512sums:-}" ] && _algo=sha256sum

	if [ -z "$_sums" ]; then
		warning "no checksums defined for $pkgname - skipping verification"
		return 0
	fi

	if ! command -v "$_algo" >/dev/null 2>&1; then
		warning "$_algo not available - skipping checksum verification"
		return 0
	fi

	# blank lines are common in a quoted multiline sha*sums= value (as
	# written in Unix/asn1c/APKBUILD) - sha256sum/shasum both warn on them
	# as "improperly formatted" even though they're otherwise harmless, so
	# strip them before verifying.
	(cd "$srcdir" && printf '%s\n' "$_sums" | grep -v '^[[:space:]]*$' | "$_algo" -c -) ||
		die "checksum verification failed for $pkgname"
}

default_prepare() {
	for _src in $source; do
		case "$_src" in
		*.patch)
			_fname=$(filename_from_uri "$_src")
			(cd "$builddir" && patch -p1 <"$srcdir/$_fname") ||
				die "failed to apply patch $_fname"
			;;
		esac
	done
}

# ---------------------------------------------------------------------------
# CBUILD/CHOST split - derived from abuild's cross_compiling()/cross_creating()
# plus its makedepends_build/makedepends_host convention. CBUILD is the
# machine actually running this build (always guess_triplet()); CHOST is what
# the output is for (defaults to CBUILD, override with build.sh's -t/--host).
# makedepends_build-class deps (protoc: must execute during this build) stage
# into NATIVE_ROOT and go on PATH; depends/makedepends_host-class deps
# (libprotobuf: linked against, built for CHOST) stage into SYSROOT and only
# ever contribute compiler/linker flags, never PATH.
# ---------------------------------------------------------------------------

cross_compiling() {
	[ "$CBUILD" != "$CHOST" ]
}

# ---------------------------------------------------------------------------
# Subpackage splitting - derived from abuild's amove/default_dev/default_doc/
# default_static/default_libs. Pure file-moving over $pkgdir into a fresh
# $subpkgdir, no apk involvement in the original either. A recipe can
# override any of these by defining its own same-named function.
# ---------------------------------------------------------------------------

# amove PATH... - move each given $pkgdir-relative path (file, whole
# directory, or an already shell-glob-expanded list of either) into
# $subpkgdir, preserving its location; a path that doesn't exist (e.g. an
# unmatched glob, which POSIX sh leaves as the literal pattern string) is
# silently skipped, not an error - ported directly from abuild.in's amove().
# Callers write bare globs (e.g. `amove usr/lib/*.so.[0-9]*`) that the shell
# expands against cwd, which build.sh sets to $pkgdir before calling any
# split function - same as real abuild's pre_split().
amove() {
	for _f in "$@"; do
		_f=${_f#/}
		[ -L "$pkgdir/$_f" ] || [ -e "$pkgdir/$_f" ] || continue
		_d=${_f%/*}
		[ "$_d" = "$_f" ] && _d=.
		mkdir -p "$subpkgdir/$_d"
		mv "$pkgdir/$_f" "$subpkgdir/$_d/"
		rmdir -p "$pkgdir/$_d" 2>/dev/null || :
	done
}

# Path list ported from abuild.in's default_dev() - broader than headers
# alone: pkgconfig/aclocal/gettext data, *-config scripts, vala/gir/qt/cmake
# build-system metadata, any nested include/ directory, static libs (unless a
# separate `static` subpackage already claims them), and the unversioned .so
# symlink needed to link against the runtime lib. Trimmed of Alpine-specific
# metadata mutation (depends_dev=/pkgdesc=/install_if=) - we don't have that
# system; the file-selection logic itself is kept faithful since that's what
# makes an existing real-world APKBUILD's `dev` split actually work unchanged.
default_dev() {
	_libdirs="usr"
	[ -d "$pkgdir/lib" ] && _libdirs="lib usr"

	for _i in usr/include usr/lib/pkgconfig usr/share/pkgconfig \
		usr/share/aclocal usr/share/gettext \
		usr/bin/*-config usr/share/vala/vapi \
		usr/share/gir-[0-9]* usr/share/qt*/mkspecs \
		usr/lib/qt*/mkspecs usr/lib/cmake usr/share/cmake \
		usr/lib/glade/modules usr/share/glade/catalogs \
		$(find . -name include -type d 2>/dev/null) \
		$(subpackage_types_has static || find $_libdirs -name '*.a' 2>/dev/null) \
		$(find $_libdirs -name '*.[cho]' -o -name '*.prl' 2>/dev/null); do
		amove "$_i"
	done

	# unversioned .so symlinks - needed to link against the -libs package
	for _i in lib/*.so usr/lib/*.so; do
		amove "$_i"
	done
}

# subpackage_types_has SUFFIX - true if $subpackages already declares a
# subpackage ending in -SUFFIX (e.g. so default_dev() doesn't also grab the
# .a files a dedicated `static` subpackage wants for itself).
subpackage_types_has() {
	for _s in ${subpackages:-}; do
		case "$_s" in
		*"-$1") return 0 ;;
		esac
	done
	return 1
}

default_static() {
	_libdirs="usr/lib"
	[ -d "$pkgdir/lib" ] && _libdirs="lib usr/lib"
	amove $(find $_libdirs -name '*.a' 2>/dev/null)
}

default_libs() {
	amove lib/lib*.so.[0-9]* usr/lib/lib*.so.[0-9]*
}

default_doc() {
	for _i in doc man info html sgml licenses gtk-doc ri help; do
		amove usr/share/"$_i"
	done
}

# ---------------------------------------------------------------------------
# Packaging: tar the populated pkgdir, write a bare-hex sha256 alongside it
# (certutil -hashfile comparable - no filename column) into
# $DESTDIR/<archdir>/<pkgname>-<pkgver>-r<pkgrel>.tar.gz
# ---------------------------------------------------------------------------

package_output() {
	_archdir="$1"
	_srcdir="${2:-$pkgdir}"
	_namesuffix="${3:-}"
	_outdir="$DESTDIR/$_archdir"
	mkdir -p "$_outdir"
	_out="$_outdir/${pkgname}${_namesuffix}-${pkgver}-r${pkgrel}.tar.gz"

	(cd "$_srcdir" && tar -czf "$_out" .)

	if command -v sha256sum >/dev/null 2>&1; then
		sha256sum "$_out" | awk '{print $1}' >"$_out.sha256"
	elif command -v shasum >/dev/null 2>&1; then
		shasum -a 256 "$_out" | awk '{print $1}' >"$_out.sha256"
	else
		warning "no sha256sum/shasum available - skipping checksum output"
	fi

	echo "$_out"
}
