#!/bin/bash
# processing command line arguments
# Check commandline arguments
if [ $# -lt 1 ]
then
    RESEARCH_BUILD=`pwd`"/build"
    RESEARCH_STAFF=$RESEARCH_BUILD  #directory for staff and wg files
    RESEARCH_TOPICS=`pwd`
    echo -e "No building directory was specified."
elif [ $# -lt 2 ] 
then
    RESEARCH_BUILD="$1"
    RESEARCH_STAFF=$RESEARCH_BUILD
    RESEARCH_TOPICS=$RESEARCH_BUILD
    echo -e "No extra topics directory was specified."
elif [ $# -lt 3 ]
then
    RESEARCH_BUILD="$1"
    RESEARCH_STAFF=$RESEARCH_BUILD
    RESEARCH_TOPICS="$2"
else
    RESEARCH_BUILD="$1"
    RESEARCH_TOPICS="$2"
    RESEARCH_STAFF="$3"
fi
mkdir -p $RESEARCH_BUILD
mkdir -p $RESEARCH_STAFF
echo -e "Building into directory $RESEARCH_BUILD ..."
echo -e "Using .md-files from $RESEARCH_TOPICS ..."
echo -e "Building into directory $RESEARCH_BUILD ..."
echo -e "Building staff-files into directory $RESEARCH_STAFF ..."
#rm -rf $RESEARCH_BUILD 

baseurl='https://www.mat.tuhh.de'

#build index.html
#replace working group
#echo "Preprocessing Working Groups"
cp $RESEARCH_ROOT/static/index.md $RESEARCH_BUILD/index.md
#$RESEARCH_ROOT/bin/preproc_wg.sh $RESEARCH_BUILD/index.md $RESEARCH_BUILD >> $RESEARCH_BUILD/build.log 2>&1
#
##replace staff names
#echo "Preprocessing Staff"
#$RESEARCH_ROOT/bin/preproc_staff.sh $RESEARCH_BUILD/index.md $RESEARCH_BUILD >> $RESEARCH_BUILD/build.log 2>&1
#
##finalize file
#sed -i -e "s;\](/img/;\](./img/;g" -e '/PROCESSED AUTOMATICALLY/ d' $RESEARCH_BUILD/index.md


#build rest of the topics
for f in $RESEARCH_TOPICS/*.md
do
    filename=$(basename -- "$f")
    #make output copy
    cp $f $RESEARCH_BUILD/$filename

    #extract title of topic
    title=`$RESEARCH_ROOT/bin/extract_title.sh $RESEARCH_BUILD/$filename`
    echo "Preprocessing topic $title"

    # append research topic to index
    echo -e "\n$title\n" >>  $RESEARCH_BUILD/index.md

    #replace working group
    $RESEARCH_ROOT/bin/preproc_wg.sh $RESEARCH_BUILD/$filename $RESEARCH_BUILD $RESEARCH_STAFF >> $RESEARCH_BUILD/build.log 2>&1

    #replace staff names
    $RESEARCH_ROOT/bin/preproc_staff.sh $RESEARCH_BUILD/$filename $RESEARCH_BUILD $RESEARCH_STAFF >> $RESEARCH_BUILD/build.log 2>&1

    #finalize file
    sed -i "s;\](/img/;\](./img/;g" $RESEARCH_BUILD/$filename
done

echo "Finished preprocessing topics."
