#!/bin/bash

addConfigureAC () {

BaseName=$1
BaseNameUpper=$( echo ${BaseName} | tr '[:lower:]' '[:upper:]' )

ConfFiles1=""
for a in $*; do
    ConfFiles1="${ConfFiles1} src/${a}/${a}Config.h:config.h.in"
done
ConfFiles=$(echo ${ConfFiles1} | xargs)

    cat - > configure.ac <<CONFIGUREAC
AC_INIT([$(basename $(pwd))], [0.1], [YourName+$(basename $(pwd))@Email.com])
AC_PREREQ([2.65])

AC_CONFIG_MACRO_DIR([build/autotools/m4])
AC_CONFIG_AUX_DIR([build/autotools/build])

AX_THOR_FUNC_INIT_BUILD([${BaseName}], [src/${BaseName}/${BaseName}.cpp])


#
# Add extra configuration here
#


LT_INIT

AX_THOR_FEATURE_HEADER_ONLY_VARIANT([${BaseNameUpper}])
AX_THOR_FUNC_TERM_BUILD([${BaseNameUpper}], [${ConfFiles}])

AC_OUTPUT
CONFIGUREAC
}

addMakeFile () {

    mkdir -p $1
    cat - > $1/Makefile <<Makefile
THORSANVIL_ROOT             = \$(realpath $2)

TARGET                      = $3

include \$(THORSANVIL_ROOT)/build/tools/$4
Makefile
}

addMakeFileExtra () {

    #
    # These files are simply included to prevent automake from erroring.
    # Please don't use them for anything.
    echo "" > Makefile.extra.am
    echo "" > Makefile.extra.in
}

addMakeFileConfig () {

    cat - >> Makefile.config.in << MakefileConfig

# In this file add the variables defined with AC_SUBST
# They can then be included by surrounding with @
# AC_SUBST([ExampleMakeFileVariable], [ValueOfVariable])
ExampleMakeFileVariable=@ExampleMakeFileVariable@
MakefileConfig

}

addConfigHIN () {

    touch config.h.in
# This file will be autogenerated after autoreconf is run
# It uses the values defined by AC_DEFINE and AC_DEFINE_UNQUOTED
# AC_DEFINE([VarName], [Value], [Help displayed by config tools])
# AC_DEFINE_UNQUOTED([AnotherName],   [$variableToExpand],   [Help displayed by config tools])
    rm config.h.in

}

addGitIgnore () {

    cat - >> .gitignore << GitIgnore
*.o
*.lex.cpp
.*.swp
*.gcov
confdefs.h

.claude
.clangd

unittest

coverage/
debug/
release/
profile/
report/
vera/
makedependency/
buildmeta/

makefile_tmp
Makefile.extra
Makefile.config

aclocal.m4
autom4te.cache/

config.log
config.status

libtool
stamp-*

config.h
${1}Config.h
MockHeaderInclude.h
GitIgnore

}

usage1 () {
    echo "We were expecting this to be a git repository"
    echo
    echo "Create one with: "
    echo "    git init"
    exit
}

usage2 () {
    echo "First time usage. Please provide the name of your package you want to build"
    echo
    echo "Exmaple:"
    echo "    # This will set up a basic project for building the shared library BobsPastry.so"
    echo "    ./Notes BobsPastry"
    echo
    echo "    # This will set up a project for building multiple shared library Bobs.so Pastry.so And.so Tarts.so"
    echo "    ./Notes Bobs Pastry And Tarts"
    echo
    exit
}

checkForBuildTools () {

    if [[ ! -e build/Notes ]]; then
        echo "Installing ThorMaker"
        git submodule init
        git submodule add https://github.com/Loki-Astari/ThorMaker.git build
        ln -s build/autotools/Notes .
        git add Notes
    fi
}

fixConfigHIn() {

    grep -A1 -B2 HEADER_ONLY config.h.in > config.HO

    grep -v HEADER_ONLY config.h.in | awk '/^#define  [A-Z_]*_CONFIG_H$/ {print $0;print "#ifndef  THORS_PACKAGE_INFO_CONFIG_H"; print "#define  THORS_PACKAGE_INFO_CONFIG_H";next;} /^#endif$/ {next;} {print $0}' > config.tmp
    echo "#endif" >> config.tmp
    echo "" >> config.tmp
    cat config.HO >> config.tmp
    echo "" >> config.tmp
    echo "#endif" >> config.tmp

    mv config.tmp config.h.in 
    rm config.HO
}

startConfigure() {

    echo "Starting Configuration"
    if [[ ! -e configure.ac ]]; then

        if [[ ! -e .git ]]; then
            usage1
        fi
        if [[ "$#" == "0" ]]; then
            usage2
        fi
        echo "Building Example Configuration"
        BaseName=$*

        checkForBuildTools

        echo "Creating Base Autotools Files"
        addConfigureAC ${BaseName}
        addMakeFile . ./ src Project.Makefile
        addMakeFile src ../ "$*" Project.Makefile
        addMakeFileExtra
        addMakeFileConfig
        addConfigHIN
        addGitIgnore ${BaseName}

        echo "Initial run of Autotools"
        autoreconf --install
        echo "" > Makefile.extra.in

        echo "Install First Source Files"
        for a in $*; do
            mkdir -p src/${a}
            echo "#include \"${a}.h\""       > src/${a}/${a}.cpp
            echo "#include \"${a}Config.h\"" > src/${a}/${a}.h 
            addMakeFile src/${a} ../../ ${a}.slib Makefile
        done

        fixConfigHIn

        echo "Adding base files to git"
        git add Notes
        git add configure configure.ac
        git add Makefile.config.in
        git add Makefile.extra.am Makefile.extra.in
        git add Makefile src/Makefile
        git add config.h.in
        git add .gitignore

        for a in $*; do
            git add src/${a}/${a}.cpp src/${a}/${a}.h src/${a}/Makefile
        done
        exit
    fi

    echo "Configuring"
    rm configure
    autoreconf --install
    cat - configure << SUBMODULE_UPDATE > config.tmp
#!/bin/sh

if git submodule status | grep build | grep --quiet '^-'; then
    git submodule update --init --recursive build
fi

SUBMODULE_UPDATE
    mv config.tmp configure
    chmod +x configure
    echo "" > Makefile.extra.in

    fixConfigHIn

    rm -f configure~
    rm -f config.h.in~
    rm -f confdefs.h

    git submodule update --recursive
}

checkAutoTools() {
   autoreconf --version > /dev/null
   if [[ $? != 0 ]]; then
       echo "Can not find autotools"
       echo "Please install"
       echo
       echo "On a mac use: brew install autoconf automake libtool"
       exit 1
   fi
}


checkAutoTools
startConfigure $1

