#!/bin/bash
set -u
#------------------------------------------------------------------------------
# Wrapper for executing ShellCheck as root. This avoids an error that looks
# something like this:
#
# foo.sh: foo.sh: openBinaryFile: does not exist (No such file or directory)
# Set HomeTmp to a directory under the ~root home directory.
declare HomeTmp=~/.tmp/ShellCheck
declare ShellCheckRCFile=
declare -i ErrorCount=0
declare -i Debug=${SC_DEBUG:-0}
declare -i ShellCheckRCSkipped=0
declare -i FileCount=0
function msg () { echo -e "$*";}
function dbg () { [[ "$Debug" -eq 0 ]] || msg "DEBUG: $*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "$ErrorCount"; }
[[ "$Debug" -ne 0 ]] && set -x
[[ -d "$HomeTmp" ]] || mkdir -p "$HomeTmp"
for f in "$@"; do
FileCount+=1
dbg "D1=$f"
if [[ "$f" == "./"* ]]; then
dbg "TWEAKING"
tgtFile="$PWD/${f#./}"
dbg "D2A=$tgtFile"
elif [[ "$f" == "/"* ]]; then
tgtFile="$PWD/$f"
dbg "D2B=$tgtFile"
else
tgtFile="$f"
dbg "D2C=$tgtFile"
fi
#tgtFile="${tgtFile#$PWD/}"
#dbg "D3=$tgtFile"
#tgtFile="${tgtFile/\/\//\//g}"
#dbg "D4=$tgtFile"
#dbg "D5=$HomeTmp/$tgtFile"
ShellCheckRCFile=
ShellCheckRCSkipped=0
if [[ -e "$tgtFile" ]]; then
[[ -d "$(dirname "$HomeTmp/$tgtFile")" ]] || mkdir -p "$(dirname "$HomeTmp/$tgtFile")"
if [[ -r .shellcheckrc ]]; then
ShellCheckRCFile="$PWD/.shellcheckrc"
dbg "cp -f .shellcheckrc \"$(dirname "$HomeTmp/$tgtFile")/.\""
cp -f .shellcheckrc "$(dirname "$HomeTmp/$tgtFile")/." ||\
ShellCheckRCSkipped=0
fi
rm -f "$HomeTmp/$tgtFile"
dbg "JUST BEFORE COPY [File $FileCount]: ls -l \"$tgtFile\""
[[ "$Debug" -eq 0 ]] || ls -l "$tgtFile"
dbg "cp -f \"$tgtFile\" \"$HomeTmp/$tgtFile\""
if cp -f "$tgtFile" "$HomeTmp/$tgtFile"; then
cd "$HomeTmp" || bail "Could not do: cd \"$HomeTmp\""
if shellcheck "$tgtFile"; then
if [[ -n "$ShellCheckRCFile" ]]; then
if [[ "$ShellCheckRCSkipped" -eq 0 ]]; then
msg "PASS ShellCheck $tgtFile (using .shellcheckrc)."
else
msg "PASS ShellCheck $tgtFile (but could not use .shellcheckrc)."
fi
else
msg "PASS ShellCheck $tgtFile"
fi
else
if [[ -n "$ShellCheckRCFile" ]]; then
if [[ "$ShellCheckRCSkipped" -eq 0 ]]; then
errmsg "FAIL ShellCheck $tgtFile (using .shellcheckrc)"
else
errmsg "FAIL ShellCheck $tgtFile (but could not use .shellcheckrc)"
fi
else
errmsg "FAIL ShellCheck $tgtFile"
fi
fi
else
errmsg "FAIL to call ShellCheck - could not copy \"$tgtFile\" to \"$HomeTmp/$tgtFile\"."
fi
# Remove copied .shellcheckrc files to avoid cacheing side effects.
find "$HomeTmp"/ -type f -name .shellcheckrc -exec rm -f {} \;
else
errmsg "FAIL - could not find file: \"$tgtFile\""
fi
done
exit "$ErrorCount"