#!/usr/bin/env bash

##############################
#use this modified script in Hochautomatisiertes-Fahren/documentation/mainDocument/sections
##############################

touch sourcecode.tex
tex_file="sourcecode.tex"
#tex_file=$(mktemp) ## Random temp file name
 
if [ $? -ne 0 ]; then
    echo "ERROR: failed to create temporary file"
    exit 1;
fi
 
# DOCUMENT HEADER

cat<<EOF >$tex_file   ## Print the tex file header
\section{Anhang}
\subsection{Quellcode}

EOF
 
###############
 
# ask the user which file extensions to include
 
#read -p "Provide a space separated list of extensions to include (default is 'h cpp qml') : " answer
# 
#if [[ $answer == "" ]]; then
#    answer="h cpp qml"
#fi

answer="c cpp h py"

# replace spaces with double escaped pipe using substring replacement  http://www.tldp.org/LDP/abs/html/parameter-substitution.html
 
extensions="${answer// /\\|}"
 
###############
 
# FINDING FILES TO INCLUDE
# inline comments http://stackoverflow.com/questions/2524367/inline-comments-for-bash#2524617
# not all of the conditions below are necessary now that the regex for c++ files has been added, but they don't harm
 
#echo $(echo $PWD)
cd ..
cd ..
cd ..
cd modules/catkin_ws
#echo $(echo $PWD)

filesarray=(
$(
find .                                                         `# find files in the current directory` \
        -type f                                                `# must be regular files` \
        -regex ".*\.\($extensions\)"                           `# only files with the chosen extensions (.h, .cpp and .qml) by default` \
        ! -regex ".*/\..*"                                     `# exclude hidden directories - anything slash dot anything (Emacs regex on whole path https://www.emacswiki.org/emacs/RegularExpression)` \
        ! -name ".*"                                           `# not hidden files` \
        ! -name "*~"                                           `# don't include backup files` \
        ! -name 'src2pdf'                                      `# not this file if it's in the current directory` \
		! -path "./build/*"                                    `# extra` \
		! -path "./devel/*"                                    `# extra` \
		! -path "./install/*"                                  `# extra` \
		! -path "./src/VeloxProtocolLib/*"                     `# extra` \
		! -path "./src/wiringPi/*"                             `# extra` \
		! -path "./src/MessageLib/cmake-build-debug/*"         `# extra` \
		! -path "./src/NetworkingLib/cmake-build-debug/*"      `# extra` \
		! -path "./src/PC2CarLib/cmake-build-debug/*"          `# extra` \
		! -path "./src/PlatoonProtocolLib/cmake-build-debug/*" `# extra`
))

cd ..
cd ..
cd documentation/mainDocument/sections
 
###############
 
# sort the array https://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash#11789688
# internal field separator $IFS https://bash.cyberciti.biz/guide/$IFS
 
IFS=$'\n' filesarray=($(sort <<<"${filesarray[*]}"))
unset IFS
 
###############
 
#read -p "Re-order files to place header files in front of cpp files? (y/n) : " answer
answer="y"

if [[ $answer == "y" ]] || [[ $answer == "Y" ]] ; then
    echo "Re-ordering files..."
 
    # if this element is a .cpp file, check the next element to see if it is a matching .h file
    # if it is, swap the order of the two elements
    re="^(.*)\.cpp$"
 
    # this element is ${filesarray[$i]}, next element is ${filesarray[$i+1]}
    for (( i=0; i<=$(( ${#filesarray[@]} -1 )); i++ ))
    do
        # if the element is a .cpp file, check the next element to see if it is a matching .h file
        if [[ ${filesarray[$i]} =~ $re ]]; then
            header=${BASH_REMATCH[1]}
            header+=".h"
            if [[ ${filesarray[$i+1]} == $header ]]; then
                # replace the next element in the array with the current element
                filesarray[$i+1]=${filesarray[$i]}
                # replace the current element in the array with $header
                filesarray[$i]=$header
            fi
        fi
    done
fi

if [[ ! $answer == "n" ]] && [[ ! $answer == "N" ]] ; then
    echo "Re-ordering files..."
 
    # if this element is a .cpp file, check the next element to see if it is a matching .h file
    # if it is, swap the order of the two elements
    re="^(.*)\.c$"
 
    # this element is ${filesarray[$i]}, next element is ${filesarray[$i+1]}
    for (( i=0; i<=$(( ${#filesarray[@]} -1 )); i++ ))
    do
        # if the element is a .cpp file, check the next element to see if it is a matching .h file
        if [[ ${filesarray[$i]} =~ $re ]]; then
            header=${BASH_REMATCH[1]}
            header+=".h"
            if [[ ${filesarray[$i+1]} == $header ]]; then
                # replace the next element in the array with the current element
                filesarray[$i+1]=${filesarray[$i]}
                # replace the current element in the array with $header
                filesarray[$i]=$header
            fi
        fi
    done
fi
 
###############
 
# Change ./foo/bar.src to foo/bar.src
IFS=$'\n' filesarray=($(sed 's/^\..//' <<<"${filesarray[*]}"))
unset IFS
 
###############
 

read -p "Review files found? (y/n) : " answer
 
if [[ $answer == "y" ]] || [[ $answer == "Y" ]] ; then
 
    echo "The following files will be included in the document..."
 
    for i in "${filesarray[@]}"
    do
        echo $i
    done
 
    # allow the user to abort
    read -p "Proceed? (y/n) : " answer
    if [[ $answer == "n" ]] || [[ $answer == "N" ]] ; then
        exit 0
    fi
 
fi
 
###############
 
# create a .tex file with each section on its own page
 
echo "Creating tex file..."
 
for i in "${filesarray[@]}"
do
    echo "\subsubsection{catkin\_ws/${i//_/\\_}}" >> $tex_file  # create a section for each source file
    echo "\lstinputlisting[style=customasm,title={\phantom{ }}]{../../modules/catkin_ws/$i}" >> $tex_file # place the contents of each file in a listing
    echo "\newpage" >> $tex_file   # start each section on a new page
done
 
###############
 
# run pdflatex twice to produce TOC
#echo "Creating pdf..."
#echo
 
#pdflatex $tex_file -output-directory . 
 
#if [ $? -ne 0 ]; then
#    echo "ERROR: pdflatex command failed on first run, refer to tmp.log for more information"
#    exit 1;
#fi
 
#pdflatex $tex_file -output-directory .
 
#if [ $? -ne 0 ]; then
#    echo "ERROR: pdflatex command failed on second run, refer to tmp.log for more information"
#    exit 1;
#fi
 
###############
 
#echo "Renaming output files..."
 
#echo "Done, output file is $title.pdf in this directory"
