#!/bin/bash
# make-sources-list.sh
# GPLv3+
# This will generate a list of files to be included as source code.
# Then it will generate LaTeX includes.
# A function to jump to application's root, default .../forksand-it-manual
cd $(echo $PWD | sed -e "s/\(.*\/forksand-it-manual\)\/.*/\1/") && echo "current path: $PWD"
# XXX Great cruft
# Redirect fix XXX
# No spaces in filenames, or this may go awry.
# Perhaps add QR codes like:
rootPath=$PWD
CODEDIR="$rootPath/source/resources"
cd "$CODEDIR" || exit
TEXOUT="$rootPath/source/Source-gen.tex"
# Build a grep exclude command that has file extensions to not include.
EXCLUDE="\./\.git \.csv$ \.eps \.git$ \.gz$ \.jpg$ \.ods$ \.ods\#$ \.png$ \.pdf$ \.swp$ \.svg$ \.tmp$ \.xml$ \.aux$ \.fuse_hidden.*$  \.glo$  \.gls$  \.idx$  \.ilg$  \.ind$  \.lof$  \.log$  \.lol$  _minted-.*$  \.old$  \.out$  \.swp$  \.toc$  \.zip$  \..*GPLv3.*$ LICENSE$ README.md$ \.tar$ \.tar\.bz2$ \.gitignore make-sources-list\.sh$ Thumbs\.db$ \.DS_Store$ \.git.*$"
EXCLUDEGREP="grep -v -i "
for i in $EXCLUDE 
  do EXCLUDEGREP="$EXCLUDEGREP -e $i"
done

SRCFILES=`find . -type f | sort -V | $EXCLUDEGREP`

rm -f $TEXOUT SHA256SUM
touch $TEXOUT SHA256SUM

# Make checksums
# LaTeX files to be rendered
for i in $SRCFILES
do
    # NOUNDER=`echo $i | sed -e 's/_/\\\_/g'`
    NOUNDER=`echo $i | sed -e 's/_/\\\\char\\\`_/g' | cut -f 2- -d "/" | sed -e 's/^\(.\{55,70\}\)\//\1\/\\\\\\\\ \\\\qquad\\\\qquad\\\\qquad\.\.\//g'`
    # !!! ToDo, apply greedy pattern to second sed's range pattern
    echo "\section{\texttt{$NOUNDER}}"
    # echo "\texttt{$NOUNDER} \\\ "
    echo "\texttt{SHA256: `sha256sum $i | cut -f 1 -d " "`}"
    sha256sum $i >> SHA256SUM
    MINTEDPATH=`echo $i | cut -f 2- -d "/"`
    MINTEDPATH="resources/$MINTEDPATH"
    if [[ "$i" =~ \.ini\.j2$|\.zone$ ]]; then
        if [[ "$i" =~ \.ini\.j2$ ]]; then
            echo "\inputminted{ini}{$MINTEDPATH}"
        else
            echo "\inputminted{ca65}{$MINTEDPATH}"
        fi
    else
        echo "\inputminted{sh}{$MINTEDPATH}"
    fi
done >> $TEXOUT

sort -V SHA256SUM > SHA256SUM.tmp
echo "There are `cat SHA256SUM | sort -u | wc -l` source code files included." > STATS
echo "There are `cat SHA256SUM.tmp | cut -f 1 -d " " | sort -u | wc -l` unique files." >> STATS

rm SHA256SUM.tmp

echo "current path: $PWD"
ssconverter spreadsheets/sharkfork.ods@"SHARKFORK Order" spreadsheets/sharkfork_order.csv

# Files not rendered
#echo "\section{Not Rendered}" >> $TEXOUT
#echo "The files listed in this section were not rendered." >> $TEXOUT
#echo "Upstream {\LaTeX} files:" >> $TEXOUT