#!/bin/sh

VERSION="2.0"

print_help()
{
    printf "%s\n" "
Usage:
any unit DATA OBJECTS

    Command to automatically build set of OBJECTS.
    Missing dependencies are installed from binary packages.
    If something is still missing, it is build before the required set.
    Then OBJECTS are build.

    Location of binary packages is given with any_pkg option.
    By default, the directory is PACKDIR.
"
}

eval "$(dumprdd -g "${@}" rdd_prf_id="output" )"
if test -z "${ANYAPI}" ; then
    printf "%s\n" "
Failed to init shell environment, needed for command execution.
The command must be launched within working directory.
Check your cmd arguments and correctness of data.
Check your dumprdd executable as well.
"
    exit 2
fi

if test -d "${any_pkg}" ; then
    pack_dir="$(cd ${any_pkg} ; pwd -P)"
else
    pack_dir="${PACKDIR}"
fi

printf "%s\n" "Collecting direct dependencies..."
deps="$( lspkg -m "${@}" | tr '\n' ',')"
deps="${deps%,}"

if test -n "${deps}" ; then
    printf "%s\n%s\n" "Deploying dependencies:" "${deps}"
    # install the needed from binaries
    any do "${@}" \
        any_pkg="${pack_dir}" \
        any_host_update=0 \
        rdd_prf_id="deploy" \
        rdd_map_entry="pkg_deploy" \
        rdd_list_entry="${deps}"

    printf "%s\n" "Calculating missing dependencies..."
    deps="$( lspkg -d "${@}" | tr '\n' ',')"
    deps="${deps%,}"
    if test -n "${deps}" ; then
        printf "%s\n%s\n" "Building the result:" "${deps}"
        any do "${@}" \
            rdd_list_entry="${deps}"
    else
        printf "%s\n" "No result in output of command:
    lspkg -d ${@}"
    fi

else
    printf "%s\n" "Dependencies are ready."
    any do "${@}"
fi
