#! /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"

	    # be nice; some makefiles expect these to exist
	    mkdir -p "$destdir/$prefix"/{include,share,lib,bin}
	    mkdir -p "$destdir/$exec_prefix"/{include,lib,bin}

	    "$make" "${make_opt[@]}" \
		    "$destdir_variable=$destdir" \
		    "${install_targets[@]}"

            # now remove the empty ones
	    rmdir "$destdir/$prefix"/{include,share,lib,bin,} > /dev/null 2>&1
	    rmdir "$destdir/$exec_prefix"/{include,lib,bin,} > /dev/null 2>&1

	    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/$(otsb_get rsync-stow-src-prefix)/" "$stowdir/$package"

	    rm -rf "$destdir"

	else
	    "$make" "${make_opt[@]}" "${install_targets[@]}"
	fi
    }

    _otsb_install-for-stow_options_before () {

	otsb_add_option bool   stow-with-destdir \
			"install for stow using the DESTDIR functionality of the makefile"

	otsb_add_option scalar destdir-variable "destdir variable name []"
	otsb_add_option scalar stowdir "stow installation directory []"
	otsb_add_option scalar rsync-stow-src-prefix "prefix to rsync to package dir in stowdir []"
	otsb_add_option array install-targets "make targets for installation [install]"
    }

    _otsb_install-for-stow_build_variables_after () {

	otsb_set destdir-variable DESTDIR
	otsb_set rsync-stow-src-prefix "$prefix"
    }

    otsb_hook_push_fn_back options_before _otsb_install-for-stow_options_before
    otsb_hook_push_fn_back build_variables_after _otsb_install-for-stow_build_variables_after

fi
