#! /bin/bash
#------------------------------------------------------------------------------
#$Author: saulius $
#$Date: 2021-05-04 04:58:48 +0000 (Tue, 04 May 2021) $
#$Revision: 8935 $
#$URL: file:///home/saulius/svn-repositories/paskaitos/VU/software/assignment-evaluation/trunk/scripts/do-check--Perl-style $
#------------------------------------------------------------------------------
#*
# Check that Perl files are written according to the guidlines.
#**

set -ue
## set -x

DIRECTORY="$1"

PENALTY_PER_CRITIQUE=10

ID='$Id: do-check--Perl-style 8935 2021-05-04 04:58:48Z saulius $'

perlcritic=perlcritic

if ! type -p $perlcritic >& /dev/null
then
    echo $0: WARNING, this script depends on the \
         \"$perlcritic\" program to check Perl style >&2
    echo "" >&2
    exit 0
fi

cd "${DIRECTORY}"

find . \
     -name .svn -prune -o \
     -name .git -prune -o \
     -name __MACOSX -prune -o \
     \( -type f -perm /111 -o -name '*.pl' \) -print \
| sort \
| while read FILE
do
    ## echo "$0: checking if I need to examine '$FILE'" >&2
    ## head -1 "$FILE" >&2
    if ( [[ $(strings "$FILE" | head -1) =~ ^#!" "*/ ]] \
             && grep -q 'bin/perl' $FILE ) || \
           [[ "$FILE" == *.pl ]]
    then
        ## echo "$0: checking file '$FILE'" >&2
        CRITIQUE="$(perlcritic -4 $FILE; STATUS=$?; \
                    if [ $STATUS = 0 -o $STATUS = 2 -o $STATUS = 3 ]; then \
                        exit 0; \
                    else \
                        exit $STATUS; \
                    fi)"
        CRITIQUE=$(echo "${CRITIQUE}" | grep -v "source OK *$"; true)
        if [ -n "$CRITIQUE" ]
        then
            COUNT=$(echo "$CRITIQUE" | wc -l)
cat <<EOF
-- [AUTO;STYLE;$(echo $ID | sed 's/\$//g')]
   Jūsų programa '$FILE' turi nusiskundimų iš $perlcritic analizatoriaus:

$(echo "$CRITIQUE" \
| sed 's/\(Code before strictures.*\)$/\1 (-20 balų)/')

EOF
        fi
    fi
done
