#!/usr/bin/env sh
set -e

# If flag/options are given that don't use the ruleset config, simply run
# svlint with the given arguments.
NONRULESET="-h|--help|-V|--version|--dump-filelist|-E|--example|--update"
if printf "%b\n" " $*" | grep -Eq " (${NONRULESET})";
then
  svlint $*
  exit $?
fi

SVLINT_CONFIG="$(dirname $(command -v svlint-style))/style.toml"

# Delete ANSI control sequences that begin with ESC and (usually) end with m.
# Delete ASCII control characters except line feed ('\n' = 0o12 = 10 = 0x0A).
SANS_CONTROL="| sed -e 's/\\o33\\[[0-9;]*[mGKHF]//g'"
SANS_CONTROL="${SANS_CONTROL} | tr -d '[\\000-\\011\\013-\\037\\177]'"

# Combine the above output sanitization fragments into variables which can be
# evaluated and processed with xargs, e.g:
#   eval "${SVFILES}" | xargs -I {} sh -c "grep foo {};"
# NOTE: Creating a variable with the result (instead of the command) would lead
# to undefined behavior where the list of file paths exceeds 2MiB.
SVFILES="svlint --dump-filelist=files $* ${SANS_CONTROL}"
SVINCDIRS="svlint --dump-filelist=incdirs $* ${SANS_CONTROL}"

TEXTWIDTH='80'
LINELEN="grep -EvIxHn --color '.{0,${TEXTWIDTH}}' {};"
LINELEN="${LINELEN} if [ \"\$?\" -eq \"0\" ]; then"
LINELEN="${LINELEN}   echo '!!! Lines longer than ${TEXTWIDTH} characters !!!';"
LINELEN="${LINELEN}   exit 1;"
LINELEN="${LINELEN} else"
LINELEN="${LINELEN}   exit 0;"
LINELEN="${LINELEN} fi"
eval "${SVFILES}" | xargs -I {} sh -c "${LINELEN}"
OBFUSTMT="grep -EIHn --color '[ ]+;' {};"
OBFUSTMT="${OBFUSTMT} if [ \"\$?\" -eq \"0\" ]; then"
OBFUSTMT="${OBFUSTMT}   echo '!!! Potentially obfuscated statements !!!';"
OBFUSTMT="${OBFUSTMT}   exit 1;"
OBFUSTMT="${OBFUSTMT} else"
OBFUSTMT="${OBFUSTMT}   exit 0;"
OBFUSTMT="${OBFUSTMT} fi"
eval "${SVFILES}" | xargs -I {} sh -c "${OBFUSTMT}"
PPDIRECTIVES="define|undef|undefineall|resetall"
PPDIRECTIVES="${PPDIRECTIVES}|ifdef|ifndef|elsif|else|endif"
PPDIRECTIVES="${PPDIRECTIVES}|include"

PPINDENT="grep -EIHn --color '[ ]+\`(${PPDIRECTIVES})' {};"
PPINDENT="${PPINDENT} if [ \"\$?\" -eq \"0\" ]; then"
PPINDENT="${PPINDENT}   echo '!!! Indented preprocessor directives !!!';"
PPINDENT="${PPINDENT}   exit 1;"
PPINDENT="${PPINDENT} else"
PPINDENT="${PPINDENT}   exit 0;"
PPINDENT="${PPINDENT} fi"
eval "${SVFILES}" | xargs -I {} sh -c "${PPINDENT}"

env SVLINT_CONFIG="${SVLINT_CONFIG}" svlint $*
