#!/bin/ash
# $Id: checksyntax,v 1.1 2005/07/01 18:44:53 vagrant Exp $

# TODO: check for POSIX compliance: POSIXLY_CORRECT

echo "Checking shell script syntax."

all_files=$(find $@ -type f | egrep -v "/tmp/|/CVS/|/TODO|/ChangeLog|/README|/THANKS|/control|/changelog|/po/|/COPYING|/*.templates|/manpages/|/configure-stamp|/.svn/")

checkShScripts () {
    regex=$1
    checkshell=$2
    sh_type=$3
    if [ -z "$(which $checkshell)" ]; then
        echo "WARNING: unable to check these scripts: $checkshell not found..."
        return 0
    fi
    FAILURES=0
    for i in $all_files ; do
        if head -n1 $i | egrep -q "${regex}" ; then
            echo -n "$i... "
            $checkshell -n $i
            syntaxOk=$?
            if [ "$checkbashisms" = "true" ] && [ "sh" = "$sh_type" ] ; then
                checkbashisms $i 
                syntaxOk=$(($syntaxOk + $? ))
            fi
            if [ "$syntaxOk" = "0" ] ; then
                echo ok
            else
                FAILURES=$(($FAILURES+1))
                echo FAIL
            fi
        fi
    done
    return $FAILURES
}

if [ -n "$(which checkbashisms)" ]; then
  checkbashisms="true"
fi

# 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

TOTAL_FAILURES=0
echo "sh scripts: (using $sh_shell)"
checkShScripts '#!/bin/sh' "$sh_shell" sh
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}
