#!/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_usage
#
# SYNOPSIS
#     . $rose_usage
#     rose_usage [CODE]
#
# DESCRIPTION
#     Prints the SYNOPSIS section of the header of $0. Expects the header to be
#     formatted like this one. If CODE is specified, exits the current shell
#     with it. If CODE is 0, prints the usage to STDOUT. If code is not 0,
#     prints the usage to STDERR.
#
# NAME
#     rose_help
#
# SYNOPSIS
#     rose_help
#
# DESCRIPTION
#     Prints help information extracted from the header of $0.
#     Suitable for use with the --help option.
#-------------------------------------------------------------------------------
function rose_usage() {
    local CODE=${1:-}
    local FD=1
    if [[ -n $CODE ]] && ((CODE != 0)); then
        FD=2
    fi
    awk '{
        if (/^# SYNOPSIS/) {
            while (getline && !/^# [A-Z]/ && !/^[^#]/) {
                if (!/^# *$/) {
                    sub(/^# */, "");
                    print "usage: " $0;
                }
            }
        }
    }' "$0" >&"$FD"
    if [[ -n $CODE ]]; then
        exit "$CODE"
    fi
}

function rose_help() {
    sed -n 's/^# //; s/^#//; /NAME/,/------/p' "$0" | head -n -1
}
