#!/usr/bin/env bash
# find-filename-conflicts - Finds cpp files with conflicting filenames
# Copyright (C) 2020  Keyboard.io, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.

## When building Kaleidoscope, the compiled object files are linked together
## into a static archive. This static archive has a very simple structure, and
## only stores filenames, not paths, not even relative ones. As such, we can't
## have files with the same name, because they will conflict, and one will
## override the other.
##
## To avoid this situation, this script will find all cpp source files (we don't
## need to care about header-only things, those do not result in an object
## file), and will comb through them to find conflicting filenames.
##
## If a conflict is found, it will print all files that share the name, and will
## exit with an error at the end. It does not exit at the first duplicate, but
## will find and print all of them.
##
## If no conflict is found, the script just prints its status message and exits
## with zero.

set -e

FILE_LIST="$(find src -name '*.cpp' | sed -e 's,\(\(.*\)/\([^/]*\)\),\3 \1,')"

exit_code=0

echo -n "Looking for conflicting filenames... "

for f in $(echo "${FILE_LIST}" | cut -f1 -d" "); do
    count=$(echo "${FILE_LIST}" | grep -c "^${f}")
    if [ "$count" -gt 1 ]; then
        echo >&2
        echo " Conflict found for ${f}: " >&2
        echo "${FILE_LIST}" | grep "${f}" | cut -d" " -f2 | sed -e 's,^,   ,' >&2
        exit_code=1
    fi
done

if [ "${exit_code}" -eq 0 ]; then
    echo "done."
fi

exit ${exit_code}