#!/bin/sh

usage()
{
cat << EOF >&2

Usage:
  -h            show this HELP message
  -d  DSTDIR    set destination directory
  -p  PROJECT   set project name (i.e. sofort)
  -n  PREFIX    set namespace prefix (i.e. sfrt)

EOF
exit 1
}

error_dstdir_exists()
{
	echo "the destination directory '$dstdir' already exists!" >&2
	exit 2
}

# one: args
dstdir=
project=
namespace=

srcdir=`dirname $0` || exit 2
cd "$srcdir" || exit 2
srcdir=`pwd` || exit 2

while getopts "hd:p:n:" opt; do
	case $opt in
	h)
  		usage
  		;;
	d)
    		dstdir="$OPTARG"
    		;;
	p)
    		project="$OPTARG"
    		;;
	n)
    		namespace="$OPTARG"
    		;;
	\?)
    		printf "Invalid option: -%s" "$OPTARG" >&2
    		usage
    		;;
	esac
done

# two: clone
if [ -z "$dstdir" ] || [ -z "$project" ] || [ -z "$namespace" ]; then
	usage
fi

stat "$dstdir" >/dev/null 2>/dev/null && error_dstdir_exists
mkdir -p "$(dirname $dstdir)" || exit 2
cp -r "$srcdir" "$dstdir" || exit 2
rm "$dstdir"/sofort.sh || exit 2
rm -rf "$dstdir"/.git || exit 2

# three: content
cd "$dstdir" || exit 2
files=$(find . -type f)
lowerspace=`echo "$namespace" | tr '[:upper:]' '[:lower:]'`_
upperspace=`echo "$namespace" | tr '[:lower:]' '[:upper:]'`_

for f in $files; do
	sed -e s/sofort/$project/g "$f" > "$f.tmp" || exit 2
	mv "$f.tmp" "$f" || exit 2

	sed -e s/sfrt_/$lowerspace/g "$f" > "$f.tmp" || exit 2
	mv "$f.tmp" "$f" || exit 2

	sed -e s/SFRT_/$upperspace/g "$f" > "$f.tmp" || exit 2
	mv "$f.tmp" "$f" || exit 2
done

# four: directory names
mv include/sofort include/$project || exit 2
dirs=$(find . -type d)

for d in $dirs; do
	name=`echo "$d" | sed -e s/sfrt_/$lowerspace/g -e s/sofort/$project/g`

	if [ "$d" != "$name" ]; then
		mv "$d" "$name" || exit 2
	fi
done

# five: file names
files=$(find . -type f)

for f in $files; do
	name=`echo "$f" | sed -e s/sfrt_/$lowerspace/g -e s/sofort/$project/g`

	if [ "$f" != "$name" ]; then
		mv "$f" "$name" || exit 2
	fi
done

# six: references
cp "$srcdir"/COPYING.SOFORT "$dstdir" || exit 2
cp "$srcdir"/src/internal/argv/argv.h "$dstdir"/src/internal/argv || exit 2

# seven: remove dummy interfaces
rm "$dstdir"/src/output/* || exit 2

recipe="$dstdir"/project/common.mk
files=$(find . -type f)

grep -v 'src/output' "$recipe" > "$recipe".tmp || exit 2
mv "$recipe".tmp "$recipe" || exit 2

for f in $files; do
	grep -v 'dummy' "$f" > "$f".tmp
	mv "$f".tmp "$f" || exit 2
done

# eight: finalize
uppername=`echo "$project" | tr '[:lower:]' '[:upper:]'`
utilcsrc=src/$project.c

sed -e s/SOFORT/$uppername/g $utilcsrc> $utilcsrc.tmp || exit 2
mv $utilcsrc.tmp $utilcsrc || exit 2

touch COPYING.$uppername || exit 2
echo "$project: project description" > README || exit 2

chmod +x sysinfo/host/host.sh || exit 2
chmod +x sysinfo/version.sh   || exit 2
chmod +x ./configure          || exit 2

# all done
exit 0
