#!/bin/ash
# $Id: checksyntax,v 1.2 2004/09/03 03:53:55 vagrant Exp $

checkShScripts () {
    regex=$1
    checkshell=$2
    FAILURES=0
    for i in $(find -type f ) ; do
        if head -n1 $i | egrep -q "${regex}" ; then
            echo -n "$i... "
            $checkshell -n $i
            syntaxOk=$?
            if [ $syntaxOk = "0" ] ; then
                echo ok
            else
                FAILURES=$(($FAILURES+1))
                echo FAIL
            fi
        fi
    done
    return $FAILURES
}

# set default /bin/sh shell
if [ -n "$(which posh)" ]; then
  sh_shell=posh
elif [ -n "$(which dash)" ]; then
  sh_shell=dash
elif [ -n "$(which ash)" ]; then
  sh_shell=ash
elif [ -n "$(which sh)" ]; then
  echo "setting /bin/sh shell to sh"
  echo "this may be a poor test if /bin/sh points to bash"
  sh_shell=sh
else
  echo "WARNING: no shell for /bin/sh found..."
fi

echo "Checking shell script syntax."

TOTAL_FAILURES=0
echo "sh scripts: (using $sh_shell)"
checkShScripts '#!/bin/sh' "$sh_shell"
TOTAL_FAILURES=$((${TOTAL_FAILURES}+$?))

echo "dash scripts:"
checkShScripts '#!/bin/dash' 'dash'
TOTAL_FAILURES=$((${TOTAL_FAILURES}+$?))

echo "ash scripts:"
checkShScripts '#!/bin/ash' 'ash'
TOTAL_FAILURES=$((${TOTAL_FAILURES}+$?))

echo "bash scripts:"
checkShScripts '#!/bin/bash' 'bash'
TOTAL_FAILURES=$((${TOTAL_FAILURES}+$?))

echo "Total errors: $TOTAL_FAILURES"
exit ${TOTAL_FAILURES}
