#!/bin/bash

if ots_build=$(pkg-config --libs ots-build) ; then
  . $ots_build
else
  echo >&2 "$0: unable to load ots-build library"
  exit 1
fi


# bash (4.1.5 at least) can't parse the function declaration if extglob is not set
# ahead of time
_mst_build_shopt_reset=$(shopt -p extglob)
shopt -s extglob

function mst-build_get_latest_archive {

    otsb_is_set pkg \
	|| return 0

    local shopt_reset=$(shopt -p extglob)
    shopt -s extglob

    local candidate=(											\
	$(shopt -s extglob;										\
	  shopt -s nullglob;										\
	  otsb_join $'\n' ${packages_dir}/${pkg}-+([0-9]).+([0-9]).+([0-9])*(.+([0-9])).@(tar.gz|tgz)	\
	  | perl -lne '@x=m/(?:(\d+)\D)/g; $,=qq[\t];print $_,@x'					\
	  | sort  -k 2,2nr -k 3,3nr -k 4,4nr								\
	| cut -f 1											\
	)												\
    )

    eval $shopt_reset

    [ ${#candidate[*]} -gt 0 ] \
	&& otsbv_set archive "$candidate"
}

eval $_mst_build_shopt_reset

otsb_assert_has_command sysarch
eval $(sysarch -sh)

otsb_assert_has_command mst-dev-config
eval $(mst-dev-config --fmt bash --override)

mst-build_init () {

    otsb_set @MST_ROOT_VAR@ '@MST_ROOT@'
    otsb_set mst_root  "$@MST_ROOT_VAR@"
    otsb_set simulroot "$@MST_ROOT_VAR@/simul"

}

mst-build_options () {

    otsb_add_option scalar pkg 'package name'
    otsb_add_option bool   arch 'architecture dependent'

    otsb_set packages-dir "$simulroot/export"
    otsb_add_option scalar packages-dir 'directory containing packages []'
    otsb_set stowdir "$simulroot/pkgs"
    otsb_set stow-with-destdir true
    otsb_set prefix "$simulroot"
    otsb_default_value_of_sysplat="$platform_os_generic"

    case $OS in

        SunOS )

            otsb_set make $(command -v gmake)
            otsbv_set patch-cmd /usr/local/bin/patch
            otsb_set tar gtar
            ;;

        * )
            otsb_set make $(command -v make)
            otsb_set tar  $(command -v tar)
            ;;

    esac

    otsb_add_option scalar sysplat  "system platform name []"
    otsb_add_option scalar make     "name of the make command []"
    otsb_add_option scalar tar      "name of the tar  command []"
}

mst-build_set_build_variables () {

    # default
    otsb_set arch true

    otsb_set sysplat "$(otsb_default_value sysplat)"

    if  otsb_is_true $arch ; then
	otsb_set exec_prefix "$prefix/$sysplat"
    else
	otsb_set exec_prefix "$prefix"
    fi

    otsb_set pkg_config_dir "${exec_prefix}/lib/pkgconfig"

    export MAKE="$make"
    export TAR="$tar"
}

otsb_hook_push_back init_before 'mst-build_init'
otsb_hook_push_front options_before 'mst-build_options'
otsb_hook_push_back build_variables_before 'mst-build_set_build_variables'
otsb_hook_push_back options_after 'mst-build_get_latest_archive'


# load ots-build-autoconf
if ! _datadir=$(pkg-config --variable=datadir ots-build) ; then
  otsb_die "unable to find ots-build-autoconf data directory"
fi

source $_datadir/ots-build-autoconf
