#!/usr/bin/env bash
#-------------------------------------------------------------------------------
# Copyright (C) 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 - environment for running scientific suites and applications
#     rosie - revision/organisation of suites for identification/exploration
#     rosa - rosie's admin utilities
#
# SYNOPSIS
#     # "rose", "rosie" and "rosa" has the following interfaces:
#     rose UTIL [ARGS ...] # Invoke a utility
#     rose help            # Print help and list available utilities
#     rose help UTIL ...   # Print help for UTIL ...
#     rose version         # Print version information
#     rose version --long  # Print more version information
#
# DESCRIPTION
#     Simple launcher for utilities in the "rose", "rosie" or "rosa"
#     name-spaces. Launch a "rose", "rosie" or "rosa" utility with the given
#     ARGS.
#-------------------------------------------------------------------------------
if ${ROSE_DEBUG:-false}; then
    set -x
fi
set -eu

ROSE_NS=$(basename "$0")
ROSE_HOME_BIN="$(dirname "$0")"
ROSE_VERSION="$(python3 -c "import metomi.rose; print(metomi.rose.__version__)")"
export ROSE_NS ROSE_HOME_BIN ROSE_VERSION

# NOTE: cannot use associative array due to bash version requirement
DEAD_ENDS=(
    rose-config-edit
    rose-edit
    rose-suite-clean
    rose-suite-cmp-vc
    rose-suite-gcontrol
    rose-sgc
    rose-suite-hook
    rose-task-hook
    rose-suite-log-view
    rose-suite-log
    rose-slv
    rose-suite-restart
    rose-suite-run
    rose-suite-init
    rose-suite-scan
    rose-suite-shutdown
    rose-suite-stop
)

# NOTE: indicies must match DEAD_ENDS array
# (be very careful not to jumble them)
DEAD_END_MSGS=(
    'The Rose configuration editor has been removed, use the Cylc GUI.'
    'The Rose configuration editor has been removed, use the Cylc GUI.'
    'This command has been replaced by: "cylc clean".'
    'This command is awaiting re-implementation in Cylc8'
    'This command has been removed: use the Cylc GUI.'
    'This command has been removed: use the Cylc GUI.'
    'Command obsolete, use Cylc event handlers'
    'Command obsolete, use Cylc event handlers'
    'This command has been removed: use the Cylc GUI.'
    'This command has been removed: use the Cylc GUI'
    'This command has been removed: use the Cylc GUI'
    'This command has been replaced by: "cylc restart".'
    'This command has been replaced by: "cylc install".'
    'This command has been replaced by: "cylc install".'
    'This command has been replaced by: "cylc scan".'
    'This command has been replaced by: "cylc stop".'
    'This command has been replaced by: "cylc stop".'
)

# Print actual command of a command alias
get_alias() {
    local NAME="$1"
    sed -n 's/exec.*'"$ROSE_NS"'-\([^"]*\).*/\1/p' \
        "$ROSE_HOME_BIN/$ROSE_NS-$NAME"
}


# Print help for a given utility
help_util() {
    local NAME=$1
    local COMMAND=$ROSE_HOME_BIN/$ROSE_NS-$NAME
    if [[ ! -r $COMMAND ]]; then
        echo "$1: utility not found." >&2
        return 1
    fi
    local ALIAS
    ALIAS="$(get_alias "$NAME")"
    if [[ -n $ALIAS ]]; then
        COMMAND=$ROSE_HOME_BIN/$ROSE_NS-$ALIAS
        COMMAND=${COMMAND%% *}
    fi
    case $(head -1 -- "$COMMAND") in
    *bash*)
        awk '{
            if (/^# NAME/) {
                do {print substr($0, 3)} while (getline && !/^#----------/);
            }
        }' "$COMMAND" | "${PAGER:-less}"
        ;;
    *python*)
        $COMMAND --help | ${PAGER:-less} # FIXME: not too pretty at the moment
        ;;
    esac
    return
}

# Ensure that ITEM_STR is at the beginning of PATH_STR
path_lead() {
    local PATH_STR=$1
    local ITEM_STR=$2
    if [[ -z ${PATH_STR:-} ]]; then
        echo "$ITEM_STR"
    elif [[ "$PATH_STR" != "$ITEM_STR" && "$PATH_STR" != $ITEM_STR:* ]]; then
        while [[ "$PATH_STR" == *:$ITEM_STR ]]; do
            PATH_STR=${PATH_STR%:$ITEM_STR}
        done
        while [[ "$PATH_STR" == *:$ITEM_STR:* ]]; do
            local PATH_HEAD=${PATH_STR%:$ITEM_STR:*}
            local PATH_TAIL=${PATH_STR##*:$ITEM_STR:}
            PATH_STR="$PATH_HEAD:$PATH_TAIL"
        done
        echo "$ITEM_STR:$PATH_STR"
    else
        echo "$PATH_STR"
    fi
}


# Print Rose version
function print_version() {
    for arg in "$@"; do
        if [[ "$arg" == '--long' ]]; then
            echo "Rose $ROSE_VERSION ($ROSE_HOME_BIN)"
            return
        fi
    done
    echo "$ROSE_VERSION"
}

#-------------------------------------------------------------------------------
# if "rose x" input then set UTIL=x
UTIL="help"
if (($# > 0)); then
    UTIL=$1
    shift 1
fi

case $UTIL in
help|h|?|--help|-h)
    if (($# == 0)); then
        {
            print_version
            # shellcheck source=metomi/rose/etc/lib/bash/rose_usage
            . "$(rose resource lib/bash/rose_usage)"
            rose_usage
            echo
            echo "$ROSE_NS provides the following utilities:"
            for U in $(cd "$ROSE_HOME_BIN" && ls "$ROSE_NS-"*); do
                NAME="$(sed "s/^$ROSE_NS-\\(.*\\)\$/\1/" <<<"$U")"
                ALIAS="$(get_alias "$NAME")"
                if [[ -n $ALIAS ]]; then
                    echo "    $NAME"
                    echo "        (=$ALIAS)"
                else
                    echo "    $NAME"
                    if [[ $U == 'rose-date' ]]; then
                        # hack an exception for this lone Python command
                        # shellcheck disable=SC2026
                        echo '       '\
                             'Parse and print 1. a date time point '\
                             'or 2. a duration.'
                    else
                        sed '1,/^# DESCRIPTION$/d;{s/^# /    /;q;}' \
                            "$ROSE_HOME_BIN/$U"
                    fi
                fi
            done
        } | ${PAGER:-less}
        exit 0
    fi
    RC=0
    for U in "$@"; do
        if [[ $U == 'help' || $U == 'version' ]]; then
            continue
        fi
        help_util "$U" || RC=$?
    done
    exit $RC
    :;;
version|--version|-V)
    print_version "$@"
    exit
    :;;
doc)
    ROSE_UTIL=$UTIL
    export ROSE_UTIL
    ns_len=$(( ${#ROSE_NS}+2 ))
    for U in $(cd "$ROSE_HOME_BIN" && ls "$ROSE_NS-"*); do
        NAME="$(sed "s/^$ROSE_NS-\\(.*\\)\$/\1/" <<<"$U")"
        ALIAS="$(get_alias "$NAME")"
        if [[ -n $ALIAS ]]; then
            echo '=================================================='
            echo "${ROSE_NS} ${NAME} -> ${ROSE_NS} ${ALIAS}"
            echo '=================================================='
            echo
        else

            echo '=================================================='
            echo "$ROSE_NS $NAME"
            echo '=================================================='
            echo
            PAGER='cat'
            help_util "$(cut -c "${ns_len}-" <<<"${U}")"
            echo
        fi
    done
    exit 0
    :;;
esac

CMD="${ROSE_NS}-${UTIL}"
for i in $(seq 0 $(( ${#DEAD_ENDS[@]} - 1 ))); do
    if [[ "${DEAD_ENDS[$i]}" == "$CMD" ]]; then
        echo "${DEAD_END_MSGS[$i]}" >&2
        exit 42
    fi
done

COMMAND="$(dirname "$0")/$ROSE_NS-$UTIL"
if [[ ! -f $COMMAND || ! -x $COMMAND ]]; then
    echo "$ROSE_NS: $UTIL: unknown utility. Abort." >&2
    echo "Type \"$ROSE_NS help\" for a list of utilities." >&2
    exit 1
fi
if (($# > 0)) && [[ $1 == '--help' || $1 == '-h' ]]; then
    help_util "$UTIL"
    exit
fi
ROSE_UTIL=$UTIL
export ROSE_UTIL

exec "$COMMAND" "$@"
