#!/bin/bash

### For UNIX systems, uncomment the next line ####
# UNIX_FLAG=0
############## DO NOT EDIT BELOW #################

let errors=0
scriptPath=$(git rev-parse --show-toplevel)
scriptPath="${scriptPath}/"
tmpFile="${scriptPath}tmpLuac"
if [ $UNIX_FLAG ]
then
    luacPath="${scriptPath}luac/luac"
else
    luacPath="${scriptPath}luac/luac.exe"
fi

function syntaxCheckFile
{
    # get the filenmame from the parameter & add it to the script path
    local file="${scriptPath}$1"
  
    if [ -e "$file" ]
    then
        # redirect error to output & write to temporary file
        "$luacPath" -p "$file" > "$tmpFile" 2>&1
        # check the return value
        if [ $? -eq 1 ]
        then
            # there was an error, tell it to the user & count up
            echo $(cat "$tmpFile")
            let errors=$errors+1
        fi
    fi
}

# get the files to commit
IN=$(git diff-index --cached --name-only HEAD)
# iterate over all file names
while IFS=$'\n' read -ra ARR; do 
    for i in "${ARR[@]}"; do
        # get the index, where ending ".lua" should start
        let ind=${#i}-4
        # extract the ending
        ending=${i:$ind:4}
        # only check files with proper ending
        if [ "$ending" = ".lua" ]
        then
            syntaxCheckFile $i
        fi
    done 
done <<< "$IN"

# remove the temporary file, in case it was created
if [ -e "$tmpFile" ]
then
    rm "$tmpFile"
fi

# now tell the user the final result
echo " "
if [ $errors -eq 0 ]
then
    echo "There were no Lua syntax errors."
    echo "COMMIT ACCEPTED"
    exit 0
elif [ $errors -eq 1 ]
then
    echo "There was one Lua syntax error."
else
    echo "There were $errors Lua syntax errors."
fi
echo "COMMIT REJECTED"
exit 1
