#!/bin/sh
#
# bpm - basix package manager
#
# this toplevel "bpm" script is an orchestrator,
# most functionality is located in the lib/ scripts
set -eu

BPM_PROGVER=0.10.1

# the absolute path to bpm, this is needed so bpm can re-exec itself
# in the sandbox and into root if needed
case $0 in
    */*) self_dir=$(cd "${0%/*}" && pwd); BPM_SELF=$self_dir/${0##*/} ;;
    *) BPM_SELF=$(command -v "$0"); self_dir=${BPM_SELF%/*} ;;
esac

[ -d "$self_dir/lib/style" ] && {
    : "${BPM_LIBDIR:=$self_dir/lib}"
}
: "${BPM_LIBDIR:=/usr/lib/bpm}"
: "${BPM_CONF:=/etc/bpm/bpm.conf}"

# the core library is required before bpm.conf gets read so BPM_LIBDIR can only come
# from the environment
[ ! -f "$BPM_LIBDIR/core.sh" ] && {
    printf 'bpm: could not find core library at %s\n' "$BPM_LIBDIR" >&2
    printf 'bpm: set BPM_LIBDIR in the environment\n' >&2
    exit 1
}

# essential library loading happens here instead of lazily
for lib in core.sh template.sh db.sh fetch.sh ; do
    . "${BPM_LIBDIR}/${lib}"
done
unset lib

config_load

trap 'interrupted 130' INT
trap 'interrupted 143' TERM
trap 'interrupted 129' HUP

usage() {
    cat >&2 <<EOF
bpm $BPM_PROGVER - basix package manager

usage: bpm <command> [argument ...]

  [b]uild    pkg...   build packages and any missing dependencies
  [i]nstall  pkg...   build if needed, then install into \$BPM_ROOT,
                      -y skips the prompt
  [r]emove   pkg...   remove installed packages, -a also removes the orphans
                      that leaves behind, -f skips the reverse dependency check
  autoremove          remove every orphaned package, -n lists them instead,
                      -y skips the prompt
  [u]pdate            pull repositories, rebuild and install what changed,
                      -y skips the prompt
  pin        [pkg...] pin packages at their installed version, no args
                      lists what is pinned
  unpin      pkg...   release the pin
  [p]ull              clone or pull repositories only
  [s]earch   pattern  search repositories (globs allowed)
  [q]uery    pkg      show template metadata and resolved use flags
  [a]lternatives      list alternatives, or bpm a <pkg> <path> to swap
  verify     [pkg...] list files that no longer match what was packaged,
                      -c includes config files, --overwrite <pkg> <path>
                      restores the specified file from the archive
  [l]ist     [-r] [pkg]
                      list installed packages, -r appends the reason each package
                      was installed
  [f]iles    pkg      list files owned by an installed package
  [o]wns     path     show which package owns a path
  [c]hecksum pkg      print the checksum= line for a template's dist_files
  [d]ownload pkg...   fetch dist_files only
  log        [pkg]    list build logs, or show one
  clean [all]         remove build trees and staged destdirs, "all" also
                      removes the build root base
  [h]elp, [v]ersion

config: $BPM_CONF
repos:  $BPM_REPOS
build:  ${BPM_BUILDROOT:-host}
EOF
    exit "${1:-1}"
}

# build sandboxing
sandbox() {
    [ "$BPM_SANDBOX" = 0 ] && { "$@" ; return ; }

    # TODO: bwrap at some point? might be pointless honestly
    have unshare || die "unshare(1) not found; install util-linux/busybox or set BPM_SANDBOX=0"

    set -- --mount --pid --fork --ipc --uts --mount-proc -- "$@"
    BPM_USERNS=0
    [ "$BPM_UID" != 0 ] && {
        set -- --user --map-root-user "$@"
        BPM_USERNS=1
    }

    # some bullshit languages require either this or vendoring (rust for example)
    [ "${allow_network:-no}" != yes ] && { set -- --net "$@" ; }

    export BPM_USERNS
    unshare "$@"
}

# resolving
#
# resolve <pkg>... works out what a build or install of <pkg> means
# before anything actually happens and gives:
#   install_order  runtime deps first, ending in what specifically got requested
#   build_plan  name|pkg_ver|role per package to build in build order
#     the build loop will run exactly this list

# bpm needs to refuse to do anything other than update itself if it's out of date
# unless it's been pinned by the user
bpm_outdated() {
    pkg_installed bpm && ! pkg_pinned bpm || return 1
    index_add bpm

    # bpm_new stays set, self_check reports it; the test is the return value
    bpm_new=$(index_get bpm ver)
    [ "$bpm_new" != '?' ] && [ "$(pkg_version bpm)" != "$bpm_new" ]
}

# 'bootstrapping gcc' would return 0
# 'bootstrapping gc' would return 1, no partial matching
bootstrapping() {
    case " ${BPM_BOOTSTRAP:-} " in
        *" $1 "*)
            return 0
        ;;
    esac

    return 1
}

# if a user is doing a fresh basix install the buildroot base packages havent been built
# so the packages to form that base need to be built raw against the host
self_check() {
    bpm_outdated || { unset bpm_new; return 0; }
    index_table
    self_set=" $(graph "$BPM_RUN/table" closure bpm) "

    for pkg; do
        case $self_set in
            *" $pkg "*)
                continue
            ;;
        esac
        die "bpm is outdated ($(pkg_version bpm) -> $bpm_new), update it first with:
        bpm update"
    done
    unset pkg

    [ -n "$BPM_BUILDROOT" ] && [ -n "$BPM_BASEPKGS" ] && {
        base_missing=$(graph "$BPM_RUN/table" unmet "$BPM_BASEPKGS" c)
        [ -n "$base_missing" ] && {
            BPM_BOOTSTRAP=$self_set
            warn "the buildroot base hasn't been built yet, building bpm's update against the host"
        }
        unset base_missing
    }

    unset self_set bpm_new
}

resolve() {
    named=$*
    index_add "$@" ${BPM_BUILDROOT:+$BPM_BASEPKGS}
    self_check "$@"
    index_table
    table=$BPM_RUN/table

    install_order=$(graph "$table" order "$named")
    graph "$table" usedeps "$install_order" "$BPM_USECONF"
    build_plan=$(graph "$table" plan "$install_order" "$named")
    plan_names=$(printf '%s\n' "$build_plan" | cut -d'|' -f1)

    # raw host builds need make_depends to be on the host and installing them
    # is the users call
    host_missing=$(graph "$table" hostdeps "$plan_names")
    [ -n "$host_missing" ] && {
        first=$(printf '%s\n' "$host_missing" | head -n1)
        pkg=${first%%|*}
        missing=${first#*|}

        die "$pkg: BPM_BUILDROOT is unset and makedepends are missing: $missing
    set BPM_BUILDROOT or put them on the host directly with:
        bpm install $missing"
    }
    unset host_missing first missing

    # the buildroot is populated from binary packages from the host
    # so those binary packages have to exist first, on a basix system
    # these should already be there
    needs_base=0
    [ -n "$BPM_BUILDROOT" ] && {
        for pkg in $plan_names; do
            bootstrapping "$pkg" || needs_base=1
        done
        unset pkg
    }

    [ "$needs_base" = 1 ] && {
        [ -n "$BPM_BASEPKGS" ] || die "BPM_BUILDROOT is set but BPM_BASEPKGS is empty, nothing to build in"
        
        base_missing=$(graph "$table" unmet "$BPM_BASEPKGS" c)
        [ -z "$base_missing" ] || die "no current binary package for build root base: $base_missing
    these have to be built against the host once, e.g.:
        BPM_BUILDROOT= bpm build $base_missing"
        unset base_missing
    }

    # install_order, build_plan, plan_names, named and table are the results,
    # unset by whoever consumes them (cmd_build, cmd_install)
    unset needs_base
}

show_builds() {
    [ -z "$build_plan" ] && { msg "nothing to build"; return 0; }

    msg "$(words "$plan_names") package(s) to build:"
    printf '%s\n' "$build_plan" | while IFS='|' read -r name ver role; do
        sub "$name $ver${role:+ ($role)}"
    done
}

show_installs() {
    msg "$(words "$install_order") package(s) to install:"
    graph "$table" versions "$install_order" | while IFS='|' read -r name ver use; do
        pkg_installed "$name" && {
            old=$(pkg_version "$name")
            if [ "$old" = "$ver" ]; then
                ver="$ver (reinstall)"
            else
                ver="$old -> $ver"
            fi
        }
        case " $named " in
            *" $name "*) ;;
            *) ver="$ver (dependency)" ;;
        esac
        sub "$name $ver"
    done
}

# archive paths for a list of indexed packages
archives_of() {
    [ -n "$1" ] || return 0
    graph "$table" versions "$1" | while IFS='|' read -r name ver use; do
        ar_path "$name" "$ver"
    done
}

# build stuff
#
# the buildroot base is shared so its populated once per run and outside any pakages log
base_ready=0
base_populate() {
    [ "$base_ready" = 0 ] || return 0
    base_set=$(graph "$table" closure "$BPM_BASEPKGS")
    stamp=$(graph "$table" versions "$base_set" | awk -F'|' '{ print $1 "@" $2 " " $3 }' | sort)
    sandbox "$BPM_SELF" __base "$stamp" $(archives_of "$base_set") ||
        die "failed to populate the build root base"

    unset stamp base_set
    base_ready=1
}

build_one() {
    if [ -n "$BPM_BUILDROOT" ] && ! bootstrapping "$1"; then
        base_populate
        deps=$(graph "$table" closure "$(index_get "$1" make_depends)")
        set -- "$1" root $(archives_of "$deps")
    else
        set -- "$1" host
    fi

    log=$BPM_LOGDIR/$1.log
    status=0

    ( tmpl_load "$1"
    [ -f "$pkg_ar" ] && [ "$BPM_FORCE" = 0 ] && {
        sub "$pkg_name: use flags changed to \"$(use_effective)\", rebuilding"
    }

    msg "building ${pkg_name}-${pkg_ver} [${build_style}] use: $(use_effective)"
    run_logged "$pkg_name-$pkg_ver" "$log" sandbox "$BPM_SELF" __stage "$@" ) || status=$?

    [ "$2" = root ] && [ "$BPM_BROOT_KEEP" = 0 ] && rm -rf "${BPM_BUILDROOT:?}/$1"
    [ "$status" = 0 ] || die "$1: build failed, full log in $log"
    unset log status deps
}

build_all() {
    # shellcheck disable=SC2086
    prefetch $plan_names
    for pkg in $plan_names; do
        build_one "$pkg"
    done
}

# commands below this point

cmd_build() {
    [ $# -gt 0 ] || usage
    builder_dirs_check
    resolve "$@"
    show_builds
    build_all
    unset install_order build_plan plan_names named table
    # pretty straight forward huh
}

cmd_install() {
    opts "y=yes" "$@"
    shift "$opt_shift"
    yes=$opt_y
    [ $# -gt 0 ] || usage

    for pkg; do
        pkg_pinned "$pkg" && {
            die "$pkg is pinned at $(pkg_version "$pkg")
    release it first with:
        bpm unpin $pkg"
        }
    done
    unset pkg

    builder_dirs_check
    resolve "$@"
    show_builds
    show_installs

    [ "$yes" = 0 ] && ! confirm "proceed?" "proceed" && {
        msg "nothing installed"
        unset yes install_order build_plan plan_names named table
        return 0
    }
    unset yes

    build_all

    # what the user requested is explicit, dependencies those explicit packages pull aren't
    # so removing the one thing that was explicitly requested makes the rest collectable
    # BPM_MARK=keep is how updates leave install reasons alone
    graph "$table" versions "$install_order" > "${BPM_RUN}/install"
    set --
    last_mark=
    while IFS='|' read -r pkg ver use; do
        case " $named " in
            *" $pkg "*)
                mark=${BPM_MARK:-explicit}
            ;;
            *)
                mark=auto # oh hi mark
            ;;
        esac
        
        [ "$mark" != "$last_mark" ] && {
            set -- "$@" "--${mark}"
            last_mark=$mark
        }

        archive=$(ar_path "$pkg" "$ver")
        # root reads the db entry next to the archive, make sure its actually there
        ar_meta "$archive" || die "$pkg: $archive has no database entry"
        set -- "$@" "$archive"
    done < "${BPM_RUN}/install"
    unset last_mark mark archive pkg ver use install_order build_plan plan_names named table

    as_root "$BPM_SELF" __install "$@"
}

cmd_remove() {
    opts "a=autoremove A=no-autoremove f=force" "$@"
    shift "$opt_shift"
    sweep=$BPM_AUTOREMOVE
    [ "$opt_a" = 1 ] && sweep=1
    [ "$opt_A" = 1 ] && sweep=0
    [ $# -gt 0 ] || usage
    require_installed "$@"

    [ "$opt_f" = 0 ] && {
        db_table
        held=$(graph "${BPM_RUN}/db" held "$*")
        [ -z "$held" ] || die "these would be left with missing dependencies: $held
    remove them too or pass -f to do it anyway"
    }

    # the sweep is part of the same removal instead of running after it
    # so there's only one escalation and one pass over the disk
    removing=$*
    [ "$sweep" = 1 ] && {
        orphans=$(pkg_orphans "$@" | tr '\n' ' ')
        [ -n "$orphans" ] && msg "also removing orphaned: $orphans" && removing="$removing $orphans"
    }

    # shellcheck disable=SC2086
    removing=$(remove_order $removing)
    # shellcheck disable=SC2086
    as_root "$BPM_SELF" __remove $removing

    [ "$sweep" = 0 ] && {
        orphans=$(pkg_orphans)
        [ -z "$orphans" ] || warn "$(words "$orphans") package(s) are now orphaned, remove them with 'bpm autoremove'"
    }
    unset sweep held removing orphans
}

cmd_autoremove() {
    opts "n=dry-run y=yes" "$@"
    shift "$opt_shift"
    [ $# -eq 0 ] || die "autoremove takes no package arguments (look at 'bpm help')"
    orphans=$(pkg_orphans)
    [ -z "$orphans" ] && {
        msg "no orphaned packages"
        return 0
    }

    # shellcheck disable=SC2086
    orphans=$(remove_order $orphans)
    msg "$(words "$orphans") orphaned package(s):"
    for pkg in $orphans; do
        sub "$pkg $(pkg_version "$pkg")"
    done
    unset pkg
    [ "$opt_n" = 0 ] || { unset orphans; return 0; }

    # bpm chose these instead of the user so just make sure
    [ "$opt_y" = 0 ] && ! confirm "remove these?" "remove these" && { msg "nothing removed" ; unset orphans ; return 0 ; }

    # shellcheck disable=SC2086
    as_root "$BPM_SELF" __remove $orphans
    unset orphans
}

cmd_pull() {
    [ -r "$BPM_REPOCONF" ] || die "no repository list at $BPM_REPOCONF"
    as_root "$BPM_SELF" __pull
}

cmd__pull() {
    while read -r name url branch; do
        case $name in ''|\#*) continue;; esac
        case $url in /*) continue ;; esac

        dir=${BPM_REPODIR}/${name}
        if [ -d "${dir}/.git" ]; then
            msg "pulling $name"
            # checkout chowned to a user as a workaround for unpriv'd
            # pulls would be dubious ownership otherwise
            git -c safe.directory="$dir" -C "$dir" pull -q --ff-only
        else
            msg "cloning $name from $url"
            mkdir -p "${dir%/*}"
            git clone -q ${branch:+--branch "$branch"} "$url" "$dir"
        fi
    done < "$BPM_REPOCONF"
    unset name url branch dir
}

cmd_update() {
    opts "y=yes" "$@"
    shift "$opt_shift"
    # not "yes": cmd_install unsets that, and the self-update path needs this
    # again after cmd_install has run
    yes_arg=; [ "$opt_y" = 1 ] && yes_arg=-y
    [ $# -eq 0 ] || die "update takes no package arguments (look at 'bpm help')"
    cmd_pull

    installed=$(pkg_all)
    # shellcheck disable=SC2086
    index_add $installed
    index_table
    graph "${BPM_RUN}/table" usedeps "$installed" "$BPM_USECONF"
    unset installed
    db_table

    # installed vs what the templates would build right now
    # three lines, packages that arent in a repo anymore, pinned ones held, and the rest
    awk -F'|' '
        FILENAME == ARGV[1] { ver[$1] = $2; use[$1] = $3; next }
        ver[$1] == "?"     { gone = gone " " $1; next }
        $2 != ver[$1] || $3 != use[$1] {
            if (index($8, "p")) held = held " " $1; else outdated = outdated " " $1
        }
        END { print gone; print held; print outdated }
    ' "$BPM_RUN/index" "$BPM_RUN/db" > "$BPM_RUN/changes"
    { read -r gone; read -r held; read -r outdated; } < "${BPM_RUN}/changes"

    for pkg in $gone; do
        warn "$pkg: no longer in any repository"
    done

    [ -z "$held" ] || msg "pinned, not updating: $held"
    [ -z "$outdated" ] && {
        if [ -n "$held" ]; then
            msg "nothing else to update"
        else
            msg "everything is up to date"
        fi
        unset pkg gone held outdated yes_arg
        return 0
    }
    unset gone held

    msg "to update: $outdated"

    # any packages that came through as dependencies need to stay marked as dependencies
    BPM_MARK=keep

    # bpm and what it depends on go first and then the rest is done by the new bpm
    bpm_outdated && {
        self_set=" $(graph "${BPM_RUN}/table" closure bpm) " self= rest=
        for pkg in $outdated; do
            case $self_set in
                *" $pkg "*)
                    self="$self $pkg"
                ;;
                *)
                    rest="$rest $pkg"
                ;;
            esac
        done
        unset self_set pkg

        [ -n "$rest" ] && {
            msg "bpm is out of date, updating it before anything else"
            # shellcheck disable=SC2086
            cmd_install $yes_arg $self
            # still outdated means the user said no
            bpm_outdated && return 0
            msg "continuing the update with the new bpm"
            rm -rf "$BPM_RUN"
            exec "$BPM_SELF" update $yes_arg
        }
    }

    # shellcheck disable=SC2086
    cmd_install $yes_arg $outdated
    unset yes_arg outdated self rest pkg
}

cmd_pin() {
    [ $# -eq 0 ] && {
        pins=$(for pkg in $(pkg_all); do if pkg_pinned "$pkg"; then printf '%s\n' "$pkg $(pkg_version "$pkg")"; fi; done)
        if [ -n "$pins" ]; then
            printf '%s\n' "$pins"
        else
            msg "nothing is pinned"
        fi
        unset pins pkg

        return 0
    }

    require_installed "$@"
    as_root "$BPM_SELF" __pin "$@"
}

cmd_unpin() {
    [ $# -gt 0 ] || usage
    require_installed "$@"
    as_root "$BPM_SELF" __unpin "$@"
}

cmd_search () {
    [ $# -gt 0 ] || usage
    for repo in $BPM_REPOS; do
        for template in "$repo"/*/template "$repo"/*/*/template "$repo"/*/*/*/template; do
            [ -f "$template" ] || continue
            name=${template%/template}; name=${name##*/}
            # shellcheck disable=SC2254
            case $name in
                $1|*$1*)
                    printf '%s\t%s\n' "$name" "$repo"
                ;;
            esac
        done
    done
    unset repo template name
}

# i'm so sorry
# this is more legible than it used to be though
cmd_query() {
    [ $# -gt 0 ] || usage
    # checked out here: inside the pipeline below a die would leave awk's status
    pkg_find "$1" > /dev/null || die "package '$1' not found in any repository"
    width=0
    [ -t 1 ] && {
        case ${COLUMNS:-} in
            ''|0|*[!0-9]*)
                width=80
            ;;
            *)
                width=$COLUMNS
            ;;
        esac
    }

    field() { field_name=$1; set -f; set -- $2; set +f; printf '%s\t%s\n' "$field_name" "$*"; }

    ( tmpl_load "$1"
      field pkg_name "$pkg_name"
      field version "$version"
      field revision "$revision"
      field build_style "$build_style"
      field short_desc "${short_desc:-}"
      field home_page "${home_page:-}"
      field license "${license:-}"
      field depends "${depends:-}"
      field make_depends "${make_depends:-}"
      field use_depends "${use_depends:-}"
      field use_flags "${use_flags:-}"
      field use "$(use_effective)"
      [ -n "${system_accounts:-}${system_groups:-}" ] && {
            field accounts "${system_accounts:-}"
            field groups "${system_groups:-}"
      }
      [ -z "${register_shell:-}" ] || field shells "$register_shell"
      field template "$tmpl_dir/template"
      if pkg_installed "$1"; then
          pin=; if pkg_pinned "$1"; then pin=', pinned'; fi
          field installed "$(pkg_version "$1") ($(pkg_reason "$1")$pin)"
          required_by=$(pkg_rdeps "$1")
          field 'required by' "${required_by:-nothing}"
      fi ) |
    awk -F'\t' -v width="$width" '{
        line = sprintf("%-11s", $1); len = 11
        n = split($2, word, " ")
        for (i = 1; i <= n; i++) {
            if (width > 0 && len > 11 && len + 1 + length(word[i]) > width) {
                print line; line = sprintf("%11s", ""); len = 11
            }
            line = line " " word[i]; len += 1 + length(word[i])
        }
        print line
    }'
    unset width field_name
    unset -f field
}

cmd_list() {
    opts "r=reason" "$@"
    shift "$opt_shift"
    [ $# -eq 0 ] && set -- $(pkg_all)
    require_installed "$@"

    for pkg; do
        if [ "$opt_r" = 1 ]; then
            printf '%s\n' "$pkg $(pkg_version "$pkg") $(pkg_reason "$pkg")"
        else
            printf '%s\n' "$pkg $(pkg_version "$pkg")"
        fi
    done
    unset pkg
}

cmd_alternatives() {
    [ $# -eq 0 ] && { pkg_list_alternatives; return 0;}
    [ $# -eq 2 ] || die "usage: bpm alternatives [<pkg> <path>]"

    as_root "$BPM_SELF" __swap "$1" "$2"
}

cmd_verify() {
    opts "c=config o=overwrite" "$@"
    shift "$opt_shift"
    [ "$opt_o" = 1 ] && {
        [ $# -eq 2 ] || die "usage: bpm verify --overwrite <pkg> <path>"
        as_root "$BPM_SELF" __restore "$1" "$2"
        return 0
    }

    . "${BPM_LIBDIR}/install.sh"
    BPM_VERIFY_CONFIG=$opt_c verify_unsummed=0
    [ $# -eq 0 ] && set -- $(pkg_all)
    require_installed "$@"
    status=0

    for pkg; do
        pkg_verify "$pkg" || status=1
    done
    unset pkg

    [ "$verify_unsummed" = 0 ] || warn "$verify_unsummed package(s) lack checksums and cannot be verified"
    [ "$status" = 1 ] || msg "no mismatches"

    return "$status"
}

cmd_files() {
    [ $# -gt 0 ] || usage
    require_installed "$1"
    cut -f1 "${BPM_DB}/$1/files" | sort
}

cmd_owns() {
    [ $# -gt 0 ] || usage
    case $1 in
        /*) path=$1 ;;
        *) path=$(cd "$(dirname "$1")" && pwd)/${1##*/} ;;
    esac

    owner=$(pkg_owner "$path")
    [ -n "$owner" ] || die "no package owns $path"
    printf '%s\n' "$owner"
    unset path owner
}

cmd_checksum() {
    [ $# -gt 0 ] || usage
    builder_dirs_check
    tmpl_load "$1"
    src_fetch
    sums=
    for dist in ${dist_files:-}; do
        case $dist in
            git+*)
                sums="$sums SKIP"
                continue
            ;;
        esac

        sums="$sums $(blake3 "${src_dir}/$(dist_name "$dist")")"
    done
    printf 'checksum="%s"\n' "${sums# }"
    unset sums dist
}

cmd_download() {
    [ $# -gt 0 ] || usage
    builder_dirs_check

    for pkg; do
        pkg_find "$pkg" > /dev/null || die "package '$pkg' not found in any repository"
    done
    unset pkg

    prefetch "$@"
}

cmd_log() {
    [ $# -eq 0 ] && {
        set -- "$BPM_LOGDIR"/*.log
        [ -f "$1" ] || die "no build logs in $BPM_LOGDIR"

        for log; do
            log=${log##*/}
            printf '%s\n' "${log%.log}"
        done
        unset log

        return 0
    }

    log=$BPM_LOGDIR/$1.log
    [ -f "$log" ] || die "no build log for $1 at $log"

    if [ -t 1 ] && [ -n "${PAGER:-}" ]; then
        "$PAGER" "$log"
    else
        cat "$log"
    fi
    unset log
}

cmd_clean() {
    msg "cleaning build trees"
    rm -rf "${BPM_CACHE:?}/build" "${BPM_CACHE:?}/dest" "${BPM_CACHE:?}/tmp"
    [ -n "$BPM_BUILDROOT" ] || return 0

    [ "${1:-}" = all ] && {
        msg "removing the build root base"
        rm -rf "${BPM_BUILDROOT:?}"
        return 0
    }

    for layer in "$BPM_BUILDROOT"/*/; do
        case ${layer%/} in
            */base) continue ;;
        esac
        [ -d "$layer" ] && rm -rf "$layer"
    done
    unset layer
}

# internal commands

cmd__base() {
    . "${BPM_LIBDIR}/sandbox.sh"
    broot_base "$@"
}

# stage one: inside the namespace, still on the hosts /
# this assembles the build root and chroots into it or goes straight
# to stage two if its a raw build
cmd__stage() {
    pkg=$1 where=$2
    shift 2

    [ "$where" = host ] && { unset where; cmd__build "$pkg"; return; }
    unset where

    . "${BPM_LIBDIR}/sandbox.sh"
    broot_run "$pkg" "$@"
}

cmd__build() {
    . "${BPM_LIBDIR}/build.sh"
    build_run "$1"
}

cmd__install() {
    . "${BPM_LIBDIR}/install.sh"
    mark=explicit
    for arg; do
        case $arg in
            --explicit|--auto|--keep) mark=${arg#--}; continue
            ;;
        esac

        pkg_install "$arg"
        pkg_mark_installed "$(ar_name "$arg")" "$mark"
    done
    unset mark arg
}

cmd__remove() { . "$BPM_LIBDIR/install.sh"; for pkg; do pkg_remove "$pkg"; done; unset pkg; }
cmd__swap() { . "$BPM_LIBDIR/install.sh"; pkg_swap "$1" "$2"; }
cmd__restore() { . "$BPM_LIBDIR/install.sh"; pkg_restore "$1" "$2"; }
cmd__pin() { for pkg; do pkg_pin "$pkg"; done; unset pkg; }
cmd__unpin() { for pkg; do pkg_unpin "$pkg"; done; unset pkg; }

while [ $# -gt 0 ]; do
    case $1 in
        -v|--verbose) BPM_VERBOSE=1 ;;
        -q|--quiet) BPM_VERBOSE=0 ;;
        --help|--version) break ;;
        --) shift; break ;;
        -*) die "unknown option: $1 (look at 'bpm help')" ;;
        *) break ;;
    esac
    shift
done
export BPM_VERBOSE

[ $# -gt 0 ] || usage
cmd=$1; shift
# internal commands make their own scratch space when they need it, the sandbox
# stage execs into chroot and would leave it behind
case $cmd in __*) ;; *) run_dir ;; esac

case $cmd in
    b|build) cmd_build "$@" ;;
    i|install) cmd_install "$@" ;;
    r|remove) cmd_remove "$@" ;;
    autoremove) cmd_autoremove "$@" ;;
    u|update) cmd_update "$@" ;;
    p|pull) cmd_pull "$@" ;;
    pin) cmd_pin "$@" ;;
    unpin) cmd_unpin "$@" ;;
    s|search) cmd_search "$@" ;;
    q|query) cmd_query "$@" ;;
    a|alternatives) cmd_alternatives "$@" ;;
    l|list) cmd_list "$@" ;;
    f|files) cmd_files "$@" ;;
    o|owns) cmd_owns "$@" ;;
    c|checksum) cmd_checksum "$@" ;;
    d|download) cmd_download "$@" ;;
    verify) cmd_verify "$@" ;;
    log) cmd_log "$@" ;;
    clean) cmd_clean "$@" ;;
    v|version|--version) printf 'bpm %s\n' "$BPM_PROGVER" ;;
    h|help|--help) usage 0 ;;
    __base|__stage|__build|__install|__remove|__pin|__unpin|__swap|__restore|__pull)
        "cmd_${cmd#_}" "$@" ;; # __stage -> cmd__stage
    *) die "unknown command: $cmd (try 'bpm help')" ;;
esac
