#!/bin/zsh

build_install() {
    echo "-- installing $1"

    target=$(echo "custom-$1-$BOX_SETUP_OS-$BOX_SETUP_DISTRO" | tr '-' '_')
    [[ ! -e ./installs_and_builds/$target ]] &&
        target=$(echo "custom-$1-$BOX_SETUP_OS-default" | tr '-' '_')
    [[ ! -e ./installs_and_builds/$target ]] &&
        target=$(echo "custom-$1-default" | tr '-' '_')

    [[ ! -e ./installs_and_builds/$target ]] &&
        ${=BOX_SETUP_INSTALL_COMMAND} "$1" &&
        return

    tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/$1.XXXXXXXX") || {
        echo "could not create temp dir for $1 build" && return
    }

    custom_script_path=$(pwd)/installs_and_builds/$target
    pushd $tmpdir > /dev/null
    $custom_script_path
    popd > /dev/null
}

echo "---- updating package manager / packages"
[[ -n "$BOX_SETUP_UPDATE_PKG_MANAGER_AND_DEFS_CMD" ]] &&
    ${=BOX_SETUP_UPDATE_PKG_MANAGER_AND_DEFS_CMD}
[[ -n "$BOX_SETUP_UPDATE_PKGS_CMD" ]] && ${=BOX_SETUP_UPDATE_PKGS_CMD}

echo "---- installing programs ---------------"
[[ -z $1 ]] && system_types_list="base" || system_types_list="base,$1"

echo "$system_types_list" |
    sed -E "s/,/\n/g" |
    while IFS= read -r system_type; do
        echo "-------- install for system type: $system_type"
        cat "installs_and_builds/programs_$system_type.txt" |
            while IFS= read -r program_name; do
                build_install "$program_name"
            done
    done

