#!/bin/bash

SOURCE_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )"

UNCRUSTIFY=$(command -v uncrustify)
if [ -z "$UNCRUSTIFY" ];
then
    echo "Uncrustify is not installed on your system."
    exit 1
fi

LINEUP_PARAMETERS="$SOURCE_ROOT/data/lineup-parameters"
if [ ! -x "$LINEUP_PARAMETERS" ];
then
    echo "lineup-parameters script is missing"
    exit 1
fi

patch=$(mktemp)

for DIR in $SOURCE_ROOT/embed $SOURCE_ROOT/lib $SOURCE_ROOT/src $SOURCE_ROOT/tests
do
   # Aligning prototypes is not working yet, so avoid headers
   for FILE in $(find "$DIR" -name "*.c" ! -path "*/contrib/*")
    do
        cp $FILE $FILE.check
        "$UNCRUSTIFY" -c "$SOURCE_ROOT/data/uncrustify.cfg" --replace --no-backup "$FILE.check"
        "$LINEUP_PARAMETERS" "$FILE.check" > "$FILE.temp" && mv "$FILE.temp" "$FILE.check"
        diff -u "$FILE" "$FILE.check" | sed -e "1s|--- |--- a/|" -e "2s|+++ -|+++ b/$file|" >> "$patch"
        rm $FILE.check
   done
done

if [ ! -s "$patch" ] ; then
  printf "** Commit is valid. \\o/\n"
  rm -f "$patch"
  exit 0
fi

printf "** Commit does not comply to the correct style :(\n\n"

if hash colordiff 2> /dev/null; then
  colordiff < $patch
else
  cat "$patch"
fi

printf "\n"
printf "You can apply these changed with: git apply $patch\n"
printf "\n"

exit 1
