#!/bin/bash

# Automatic makefile generation
# Jerry Cooperstein, coop@linuxfoundation.org, 2/2003 - 1/2020
# License: GPLv2

U_S=""    # list of userland programs (.c files)
U_X=""    # list of userland programs (executables) 
ALL=""    # list of all targets

#CFLAGS_U_X="-O2 -Wall -pedantic -pthread"    # compile flags for user programs
# add debug flag
#CFLAGS_U_X="-O2 -Wall -pedantic -pthread -g"    # compile flags for user programs
CFLAGS_U_X="-O2 -Wall -pthread -g"    # compile flags for user programs

# construct lists of sources and targets

# skip empty directories
if [[ -z $(find . -maxdepth 1 -name "*.c") ]] ; then 
    echo No need to make Makefile: no source code
    exit
fi

for names in *.c ; do 
    U_X=$U_X" $(basename $names .c)"
    U_S=$U_S" $names"
done

CLEANSTUFF="$U_X $T_X"

# get ALL the targets

[[ -n $U_X ]]  && ALL=$ALL" userprogs"

# echo if you are curious :>

echo U_S=$U_S U_X=$U_X T_S=$T_S T_X=$T_X

#####################################################################################
# We're done preparing, lets build the makefile finally!

# get rid of the old Makefile, build a new one

rm -f Makefile

echo "### Automatic Makefile generation by 'genmake' script        ####" >>Makefile
echo "### Copyright, Jerry Cooperstein, coop@linuxfoundation.org 2/2003 - 1/201 ####" >>Makefile
echo "### License: GPLv2 ###"                                              >>Makefile

echo -e "\nallofit: $ALL" >> Makefile

if [[ -n $U_X ]] ; then 
    echo -e "\nuserprogs:" >> Makefile
    echo -e "\t@\$(MAKE) \\" >> Makefile
    echo -e "\t\tCFLAGS=\"$CFLAGS_U_X\" \\" >> Makefile
    if [[ -n $LDLIBS ]] ; then
	echo -e "\t\tLDLIBS=\"$LDLIBS\" \\" >> Makefile
    fi
    if [[ -n $CPPFLAGS ]] ; then
    echo -e "\t\tCPPFLAGS=\"$CPPFLAGS\" \\" >> Makefile
    fi
    echo -e "\t$U_X" >> Makefile 
fi

if [[ -n $T_X ]] ; then 
    echo -e "\t@\$(MAKE) \\" >> Makefile
    echo -e "\t\tCFLAGS=\"$CFLAGS_T_X\" \\" >> Makefile
    if [[ -n $LDLIBS ]] ; then
	echo -e "\t\tLDLIBS=\"$LDLIBS\" \\" >> Makefile
    fi
    if [[ -n $CPPFLAGS ]] ; then
	echo -e "\t\tCPPFLAGS=\"$CPPFLAGS\" \\" >> Makefile
    fi
    echo -e "\t$T_X" >> Makefile 
fi

echo -e "\nclean:" >> Makefile
echo -e "\trm -rf $CLEANSTUFF" >> Makefile

exit

######################################################################################

