#!/bin/sh
#
# This script is intended to be called from a Makefile to selectively
# apply symbolic links from capitalized or camelcased filenames back to
# the original lowercased filenames.  If this happens to files in a
# filesystem that is not case-sensitive, then no links will be added.
#
# This script was written by David Griffith <dave@661.org> in 2021 and
# released to the public domain.

USAGE="usage: $0 <directory> <list-of-symlinks>"
TARGET=$1
shift

if [ -z "$TARGET" ]; then
	echo "$USAGE"
	exit 1
fi

if [ ! -d "$TARGET" ]; then
	echo "$USAGE"
	echo "$TARGET is not a directory or does not exist."
	exit 2
fi

rm -f "$TARGET"/ctest? 2> /dev/null

TOUCH="$(touch "$TARGET"/ctesta "$TARGET"/ctestA 2>&1|wc -l)"

if [ "$TOUCH" -gt 0 ]; then
	echo "$0 is unable to write to $TARGET."
	exit 3
fi

FILECOUNT="$(find "$TARGET"/ctest? | wc -l)"
rm -f "$TARGET"/ctest? 2> /dev/null

if [ "$FILECOUNT" -eq 2 ]; then
	echo "* Filesystem is case-sensitive."
	echo "* Adding symbolic links to Standard Library directory."
	cd "$TARGET" || exit
	for file in "$@"; do	\
		realfile="$(echo "$file" | tr '[:upper:]' '[:lower:]')";	\
		echo "    $file -> $realfile";			\
		test -r "$file" || ln -sf "$realfile" "$file";	\
	done
else
	echo "* Filesystem is NOT case-sensitive.";		\
	echo "* There is no need to add symbolic links to Standard Library directory."
fi

exit 0
