#!/bin/sh
# Install a package

# shellcheck disable=1091
if command -v cpt-lib >/dev/null; then . cpt-lib; else . ./cpt-lib; fi

while [ "$1" ]; do
    case "$1" in
        --help|-h)
            out "usage: ${0##*/} [options] [pkg...]" "" \
                "  Options:" \
                "    --force           Force installation" \
                "    --root [rootdir]  Use an alternate root directory" ""
            exit 1
            ;;
        --version|-v) version                ;;
        --force) export CPT_FORCE=1          ;;
        --root) export CPT_ROOT=$2; shift 2 ;;
        --) break ;;
        -*) die "Unknown argument '$1'" ;;
        *) break ;;
    esac
done

[ "$1" ] || set -- "${PWD##*/}"; export CPT_PATH=${PWD%/*}:$CPT_PATH

[ -w "$CPT_ROOT/" ] || [ "$uid" = 0 ] || {
    as_root "$0" "$@"
    exit $?
}

pkg_order "$@"

create_cache

# shellcheck disable=2154
for pkg in $order; do pkg_install "$pkg"; done

# After installation is complete, show a list of messages from packages.
log "Retrieving post-installation message queue"
unset msg

for pkg in $order; do
    [ -f "$sys_db/$pkg/message" ] && {
        printf '%s\n%s\n%s\n\n' \
               "=======================================" \
               "$pkg" \
               "======================================="
        cat "$sys_db/$pkg/message" >&2
        msg=1
    }
done
[ "$msg" ] || log "No message in queue"