#!/bin/bash
#-------------------------------------------------------------------------------
# Copyright (C) 2012-2019 British Crown (Met Office) & Contributors.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Rose is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rose. If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
# NAME
#     rose_init
#
# SYNOPSIS
#     . $ROSE_HOME/lib/bash/rose_init
#     rose_init [FUNC ...]
#
# DESCRIPTION
#     Initialise a bash script with the following:
#     * "set -eu".
#     * load the "rose_usage" function.
#     * load any FUNC specified in the argument list.
#-------------------------------------------------------------------------------
function rose_readlink_canonicalize() { # "readlink -f" is GNU extension
    readlink -f $1 2>/dev/null || python2 - $1 <<'__PYTHON__'
import os, sys
print os.path.realpath(sys.argv[1])
__PYTHON__
}

function rose_init() {
    set -eu
    ROSE_NS=$(basename $0)
    ROSE_HOME_BIN=$(cd $(dirname $0) && pwd)
    ROSE_HOME_BIN=$(rose_readlink_canonicalize $ROSE_HOME_BIN)
    ROSE_HOME=$(dirname $ROSE_HOME_BIN)
    eval $(grep 'ROSE_VERSION' $ROSE_HOME/rose-version)
    local DESC=
    if DESC=$(cd $ROSE_HOME && git describe 2>/dev/null); then
        ROSE_VERSION=$DESC
    fi
    export ROSE_HOME ROSE_HOME_BIN ROSE_NS ROSE_VERSION

    local LIB=$ROSE_HOME/lib/bash
    if [[ -f $LIB/${FUNCNAME[0]}_site ]]; then
        . $LIB/${FUNCNAME[0]}_site
    fi

    local ITEM=
    for ITEM in rose_usage $@; do
        local FILE=
        for FILE in $(ls $LIB/$ITEM 2>/dev/null); do
            . $FILE
        done
    done
}
