#! /bin/bash
# shellcheck disable=SC2154

if ! command -v otsb_cmd_install > /dev/null; then

    otsb_cmd_install () {

	otsb_setarr install-targets install

        # stow support requested
	if [ -n "${stowdir-}" ] && otsb_is_true "$stow_with_destdir" ; then

            # install using DESTDIR then move into $stowdir/$package.
            # proper use of DESTDIR will generate a directory structure
            # which is too deep for stow.  see
            #
            #    http://thread.gmane.org/gmane.comp.gnu.libtool.general/11645
            #
            # for why one cannot simply hack DESTDIR & prefix

	    otsb_assert_has_command rsync

	    local destdir
	    destdir=$(otsb_mktemp_dir) \
		|| otsb_die "unable to create temporary directory for DESTDIR installation"

	    ./Build --destdir "$destdir" \
		    "${install_targets[@]}"

            # now remove the empty ones
	    find "$destdir" -type d -empty -exec rmdir {} + 2> /dev/null

	    mkdir -p "$stowdir/$package"

	    # use rsync instead of cp to handle case where stow package
	    # directory will be the result of interleaving multiple
	    # installs. This would be the case when installing multiple
	    # architectures (same ${prefix}, different ${exec_prefix})
	    rsync -a "$destdir/$prefix/" "$stowdir/$package"
	    rm -rf "$destdir"

	else
	    ./Build "${install_targets[@]}"
	fi

    }

    _otsb_install-for-stow_init () {

	otsb_add_option bool   stow-with-destdir \
			"install for stow using the DESTDIR functionality of the makefile"
	otsb_add_option scalar stowdir "stow installation directory []"
	otsb_add_option array install-targets "make targets for installation [install]"
    }

    otsb_hook_push_fn_back options_before _otsb_install-for-stow_init
fi
