#!/bin/bash
#
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

function filterGeneratedFiles {
    for f in $@; do
        head -n2 $f | grep -qE 'Code generated by.*DO NOT EDIT' || echo $f
    done
}

function filterExcludedFiles {
  CHECK=`echo "$CHECK" \
		| grep -v "^\.git/" \
		| grep -v "^\.build/" \
		| grep -v "^vendor/" \
		| grep -v "testdata/" \
		| grep -v "swagger/" \
		| grep -v "^LICENSE$" \
		| grep -v "\.png$" \
		| grep -v "\.rst$" \
		| grep -v "\.txt$" \
		| grep -v "\.pem$" \
		| grep -v "_sk$" \
		| grep -v "\.key$" \
		| grep -v "\.gen\.go$" \
		| grep -v "^Gopkg\.lock$" \
		| grep -v "\.md$" \
		| grep -v "\.pb\.go$" \
		| grep -v ".gitignore" \
		| grep -v "ci.properties" \
		| sort -u`

  CHECK=$(filterGeneratedFiles "$CHECK")
}

CHECK=$(git diff --name-only --diff-filter=ACMRTUXB HEAD)
filterExcludedFiles
if [[ -z "$CHECK" ]]; then
  LAST_COMMITS=($(git log -2 --pretty=format:"%h"))
  CHECK=$(git diff-tree --no-commit-id --name-only --diff-filter=ACMRTUXB -r ${LAST_COMMITS[1]} ${LAST_COMMITS[0]})
  filterExcludedFiles
fi

if [[ -z "$CHECK" ]]; then
   echo "All files are excluded from having license headers"
   exit 0
fi

echo "Checking Go files for license headers ..."
missing=`echo "$CHECK" | xargs ls -d 2>/dev/null | xargs grep -L "SPDX-License-Identifier"`
if [[ -z "$missing" ]]; then
   echo "All files have SPDX-License-Identifier headers"
   exit 0
fi
echo "The following files are missing SPDX-License-Identifier headers:"
echo "$missing"
echo
echo "Please replace the Apache license header comment text with:"
echo "SPDX-License-Identifier: Apache-2.0"

missing=`echo "$missing" | xargs ls -d 2>/dev/null | xargs grep -L "Apache License"`
if [ -z "$missing" ]; then
   echo "All remaining files have Apache 2.0 headers"
   exit 0
fi

echo "The following files are missing license headers:"
echo "$missing"
exit 1
