#!/usr/bin/env bash
#
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# This program 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.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

# Wrapper for running `shellcheck` over projects.

set -e
cd "$(dirname "$0")/../../"

# find shell files under the specified directory
find_files () {
    SEARCH_PATH="$1"
    grep --color=never -rl '^#\!.*bash' "${SEARCH_PATH}" | sed 's/^\.\///'
    find "${SEARCH_PATH}" -name '*.sh' | sed 's/^\.\///'
}

main () {
    # parse CLI
    includes=()
    excludes=()
    args=()
    while [[ "$#" -gt 0 ]]; do
        if [[ ${1} == '--' ]]; then
            shift
            break
        elif [[ ${1} == "--exclude" ]]; then
            shift
            excludes+=("$1")
        elif [[ ${1} == "-*" ]]; then
            args+=("$1")
        else
            mapfile -t files < <(find_files "${1}")
            includes=("${includes[@]}" "${files[@]}")
        fi
        shift
    done

    # extract files list
    files=()
    for include in "${includes[@]}"; do
        skip=0
        for exclude in "${excludes[@]}"; do
            if [[ "${include}" == "${exclude}"* ]]; then
                skip=1
                break
            fi
        done
        if [[ $skip == 0 ]]; then
            files+=("${include}")
        fi
    done

    # sort $files removing duplicates
    readarray -t files < <(for x in "${files[@]}"; do echo "$x"; done | sort -u)

    # run shellcheck
    shellcheck "$@" "${files[@]}"
}

# default configuration for linting cylc
default () {
    # run a strict check on all "functional" scripts
    main '.' \
        --exclude '.git' \
        -- \
        -e SC1090 \
        -e SC1091
}

if [[ $# -gt 0 ]]; then
    main "$@"
else
    default
fi
