#!/bin/bash -e

if ! command -v shellcheck > /dev/null; then
    echo "E: Please install the program 'shellcheck' prior to executing this script."
    exit 1
fi

# This script is supposed to be in the scripts subdirectory
TOPDIR=$(realpath --relative-to=. "$(dirname "$0")/..")

# Exclude tracking includes and don't complain about include paths
SHELLCHECK_OPTS="--exclude=SC1090,SC1091"
export SHELLCHECK_OPTS

# Check if files are specified on the command line. If so, only use those.
if [ $# -gt 0 ]; then
    case "$1" in
    -h|--help*)
        cat <<EOF
Shellcheck script to check LinuxCNC shell scripts.
Usage: shellcheck.sh [-h|--help] [files...]
  -h, --help   This help message

Specify one or more files on the command line if you only want those files
to be checked. The script will search all of the LinuxCNC source tree for
shell scripts if no files are specified on the command line.
EOF
        exit 1
        ;;
    esac
    FILES=( "$@" )
else
    #
    # With the file command we can find all scripts.
    #   Note: perform shellcheck with a distclean tree. Some scripts are
    #   generated by configure from .in files.
    #
    # Without the file command we just look for script file names.
    #
    if [ -n "$(command -v file)" ]; then
        mapfile -t FILES < <(find "$TOPDIR" -type f \
                     -not -path "*/.git/*" \
                     -not -path "*/autom4te.cache/*" \
                     -not -name "*~" \
                     -not -path "*/tcl/*" \
                     -not -name "*.tcl" \
                     -not -name "configure" \
                     -not -name "config.guess" \
                     -not -name "config.status" \
                     -not -name "config.sub" \
                     -not -name "install-sh" \
                     -exec file {} + | awk -F: '/shell script/{print $1}')
    else
        mapfile -r FILES < <(find "$TOPDIR" -type f -name "*.sh")
    fi
fi

if [ "${#FILES[@]}" -gt 0 ]; then
    shellcheck "${FILES[@]}"
fi
