#!/bin/sh
#
# APKG - Alice Package Manager frontend (C) 2026 Atarwn
#
# Command router. Does no work itself; exec-delegates to the proper
# backend tool based on the first option:
#
#   apkg-src     -w -p -g -k            source builds and recipe utilities
#   apkg-bin     -I -U -S -R            binary package management
#   apkg-resolv  -d -dd -D -DD -j -jj   dependency graph queries
#   spm          -a -b -h -i -l -r -o -u  low-level package operations
#
# The first option determines the backend; remaining options are passed
# through unchanged. Options not listed above (-s, -t, apkg-bin extras
# like -o/-c/-l/-g) are available on the backend tools directly.
#

apkg_help() {
	cat << 'EOF'
usage: apkg <option> [arg(s)]

Command router - delegates to the proper backend tool:

  apkg-src:     -w          download source only
                -p <pkg(s)>  print package recipe path
                -g <pkg(s)>  update .shasum checksums
                -k <pkg(s)>  update .files package file list
                -s [pat]    search packages in repos
                -t [pkg(s)] run post-install triggers

  apkg-bin:     -I <pkg(s)>  install package(s) with dependencies
                -U [pkg(s)]  system update
                -S           sync binary package database
                -R <pkg(s)>  remove package(s) with dependencies

  apkg-resolv:  -d/-dd <pkg>    list <pkg> dependencies (incl. makedepends)
                -D/-DD <pkg(s)> list all dependencies in order
                -j/-jj <pkg>    list all dependents

  spm:          -a           print all installed packages
                -b          build package from current directory
                -h          print spm help message
                -i <file>   install <file> package into system
                -l <pkg>    list files installed by <pkg>
                -r <pkg>    remove installed <pkg> from system
                -o <file>   print owner of <file>
                -u <pkg>    reinstall/upgrade <pkg>

notes:
  - 'apkg -i/-u' with a package file argument runs spm; with a package
    name or from inside a recipe directory it builds from source
    (apkg-src).
  - 'apkg -h' prints this message; run 'spm -h' for spm's own help.

environment variables: see apkg-src(8), apkg-bin(8) and spm(8)

EOF
}

# -i/-u: file argument -> spm, otherwise source build via apkg-src
route_install() {
	_opt=$1
	shift
	for _a in "$@"; do
		case $_a in
			-*) continue;;
		esac
		if [ -f "$_a" ]; then
			exec spm "$_opt" "$@"
		fi
		break
	done
	exec apkg-src "$_opt" "$@"
}

case $1 in
	-h|'') apkg_help; exit 0;;
	-w|-p|-g|-k|-s|-t) exec apkg-src "$@";;
	-I|-U|-S|-R) exec apkg-bin "$@";;
	-d|-dd|-D|-DD|-j|-jj) exec apkg-resolv "$@";;
	-i|-u) route_install "$@";;
	-a|-b|-l|-r|-o) exec spm "$@";;
	-*) printf "%s\n" "apkg: invalid option '$1'" >&2; apkg_help; exit 1;;
esac

exit 0
