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

# This file is adapted two files in hyperledger/fabric scripts/functions.sh and scripts/check_license.sh
# The most recent fabric commit to edit one of these files is 3e96c2b


CHECK=$(git diff --name-only --diff-filter=ACMRTUXB HEAD | tr '\n' ' ')
if [[ -z "$CHECK" ]]; then
    CHECK=$(git diff-tree --no-commit-id --name-only --diff-filter=ACMRTUXB -r "HEAD^..HEAD" | tr '\n' ' ')
fi

function filterExcludedAndGeneratedFiles {
    local excluded_files
    excluded_files=(
        '\.block$'
        '^\.build/'
        '\.gitignore'
        '^\.gitmodules'
        '^build/'
        '_build/'
        '(^|/)ci\.properties$'
        '\.clang-format$'
        'common/crypto/pdo'
        'common/json/parson'
        'common/base64'
        'ecc/ecc$'
        'protos/fabric'
        '(^|/)\.git/'
        '\.gen\.go$'
        '(^|/)go.mod$'
        '(^|/)go.sum$'
        '(^|/)Gopkg\.lock$'
        'samples/deployment/test-network/fabric-samples/'
        '\.json$'
        '\.key$'
        '(^|/)LICENSE$'
        '\.md$'
        '\.patch$'
        '\.pb\.go$'
        '\.pem$'
        '(^|/)Pipfile$'
        '(^|/)Pipfile\.lock$'
        '\.png$'
        '\.pptx$'
        '\.rst$'
        '_sk$'
        'test_blocks/mychannel-block[0-9]{1,2}'
        '(^|/)testdata\/'
        '\.tx$'
        '\.txt$'
        '(^|/)vendor\/'
        '\.ico$'
        'common/crypto/pdo'
        'protos/fabric'
    )

    local filter
    filter=$(local IFS='|' ; echo "${excluded_files[*]}")

    read -ra files <<<"$@"
    for f in "${files[@]}"; do
        file=$(echo "$f" | grep -Ev "$filter" | sort -u)
        if [ -n "$file" ]; then
            head -n2 "$file" | grep -qE '// Code generated by' || echo "$file"
        fi
    done
}

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

missing=$(echo "$FILTERED" | sort -u |  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"

echo
echo "Checking committed files for traditional Apache License headers ..."
missing=$(echo "$missing" | xargs ls -d 2>/dev/null | xargs grep -L "http://www.apache.org/licenses/LICENSE-2.0")
if [[ -z "$missing" ]]; then
    echo "All remaining files have Apache 2.0 headers"
    exit 0
fi
echo "The following files are missing traditional Apache 2.0 headers:"
echo "$missing"
echo "Fatal Error - All files must have a license header"
exit 1
