#!/bin/bash
# Copyright 2017 Mellanox Technologies Ltd.
# Licensed under BSD (MIT variant) or GPLv2. See COPYING.


if [ "x$TRAVIS_EVENT_TYPE" != "xpull_request" ]; then
	# Peform checkpatch checks on pull requests only
	exit 0
fi

# The below "set" is commented, because the checkpatch.pl returns 1 (error) for warnings too.
# And the rdma-core code is not mature enough to be warning safe
# set -e

if [ "x$TRAVIS_COMMIT_RANGE" != "x" ]; then
	wget -q https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/scripts/checkpatch.pl \
	        https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/scripts/spelling.txt
	DIR_FOR_PATCHES_TO_CHECK=$(mktemp -d)
	git format-patch --no-cover-letter $TRAVIS_COMMIT_RANGE ^$TRAVIS_BRANCH -o $DIR_FOR_PATCHES_TO_CHECK/
	CHECKPATCH_OPT="--no-tree --ignore PREFER_KERNEL_TYPES,FILE_PATH_CHANGES,EXECUTE_PERMISSIONS,USE_NEGATIVE_ERRNO,CONST_STRUCT $DIR_FOR_PATCHES_TO_CHECK/*"
	perl checkpatch.pl $CHECKPATCH_OPT
	if [ $? -ne 0 ]; then
		# We rerun checkpatch to simplify parsing and to understand if we failed for errors
		# For example, the output on some arbitrary patchset of the following line without awk is:
		# total: 1 errors, 3 warnings, 42 lines checked
		NUMB_ERRRORS=$(perl checkpatch.pl --terse $CHECKPATCH_OPT | awk 'BEGIN {FS = "total:"} ; {sum+=$2} END {print sum}')
		exit $NUMB_ERRRORS
	fi
fi
