#!/bin/bash

if [ "$1" = "" ]; then
	echo "Usage: gen_makefile app_name"
	echo "	where app_name is source file name without extension"
	exit 0
fi

if [ "$PETSC_SCALAR_TYPE" = "" ]; then
	for i in complex real; do
		if [ -f /usr/bin/petsc-$i.sh ]; then
			PETSC_SCALAR_TYPE=$i
		fi
	done
fi
source /usr/bin/petsc-$PETSC_SCALAR_TYPE.sh

APP=$1
mv -f makefile makefile.old
cp /usr/share/petsc/makefile.tmpl ./makefile

if [ "$PETSC_SCALAR_TYPE" = "complex" ]; then
	sed -i "s|(DUMMY)|-lpetscdummy|g" makefile
else
	sed -i "s|(DUMMY)||g" makefile
fi

IS_C=$(ls $APP.c $APP.C $APP.cxx $APP.cpp 2>/dev/null |wc -l)
if [ $IS_C -eq 0 ]; then
	FSRC=$APP.F
	FAPP=$APP
	CAPP=dummy
else
	CSRC=$(ls $APP.c $APP.C $APP.cxx $APP.cpp 2>/dev/null)
	CAPP=$APP
	FAPP=dummy
fi

sed -i "s|(PWD)|$PWD|g" makefile
sed -i \
	-e "s/(FSRC)/$FSRC/g" \
	-e "s/(CSRC)/$CSRC/g" \
	-e "s/(APP)/$APP/g" \
	-e "s/(FAPP)/$FAPP/g" \
	-e "s/(CAPP)/$CAPP/g" \
	makefile

make all
