#!/bin/bash

COURSE=$(basename $(pwd))
TEXFILE="$COURSE".tex
THISDIR=$(pwd)

# decied if it is a LFS or a LFD class
APPENDICES=appendices.tex
MODULES=CHAPS


declare -a a_from_num=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

echo Making $COURSE from $TEXFILE

# make README files

# for .c and .h files and .cpp files
READMEFILE=/dev/shm/README_$RANDOM
POUNDREADMEFILE=/dev/shm/POUNDREADME_$RANDOM

cat <<EOF > $READMEFILE
/*
 * The code herein is: Copyright the Linux Foundation, 2021
 *
 * This Copyright is retained for the purpose of protecting free
 * redistribution of source.
 *
 *     URL:    https://training.linuxfoundation.org
 *     email:  info@linuxfoundation.org
 *
 * This code is distributed under Version 2 of the GNU General Public
 * License, which you should have received with the source.
 *
 */
EOF

# for .sh files and .stp files
cat <<EOF > $POUNDREADMEFILE
#/*
# * The code herein is: Copyright the Linux Foundation, 2021
# *
# * This Copyright is retained for the purpose of protecting free
# * redistribution of source.
# *
# *     URL:    https://training.linuxfoundation.org
# *     email:  info@linuxfoundation.org
# *
# * This code is distributed under Version 2 of the GNU General Public
# * License, which you should have received with the source.
# *
# */
EOF

#  get version number
VERSION=$(grep '\\newcommand{\\version}' $TEXFILE \
    | sed -e s/'\\newcommand{\\version}{'//g \
    | sed -e s/'}'//g)
echo VERSION=$VERSION

# Fix up .c and .h files

updatecsourcefile(){
    file=$1
    bn=$(basename $file)
    descname="$COURSE":"$VERSION"" $sdir/$bn"
    echo '/* **************** '$descname' **************** */' > junk0
    descname="$COURSE":"$VERSION"" $sdir\/$bn"
    cat junk0 $READMEFILE $file > junk
    sed \
	-e s/MODULE_DESCRIPTION_NAME/"$descname"/g \
	junk > $file
    rm junk junk0
}
# Fix up .sh files

updatescriptfile(){
    file=$1
    bn=$(basename $file)
    descname="$COURSE":"$VERSION"" $sdir/$bn"
# note there will be two #!/bin/bash, but seems ok. Avoids Ubuntu dash bug
    echo '#!/bin/bash' > junk0
    echo '#/* **************** '$descname' **************** */' >> junk0
    cat junk0 $POUNDREADMEFILE $file > junk
    mv junk $file
    chmod +x $file
    rm junk0
}
# use stat to find out what partition/filessystem a file is on.
get_file_device(){
    stat $1 | grep Device | awk '{print $2}'
}

hardlink_to_save_space(){
    F1=$1 ; F2=$2
    if [  "$(diff -s $F1 $F2 | grep identical)" ] ; then
	dev1=$(get_file_device $F1)
	dev2=$(get_file_device $F2)
	if [[ $dev1 == $dev2 ]] ; then
	    echo hardlinking $F1 and $F2
	    rm $F2
	    ln -v $F1 $F2 || cp -v $F1 $F2
	else
# you can't hardlink files on separate devices!
	    echo Can not Hardlink $F1 and $F2, on separate devices
	fi
    fi
}

######################################################################
# Read singular config from course tex file
read_tex() {
        local FILE=$1
        local KEY=$2

        # shellcheck disable=SC1003
	grep -E '\\(re)*newcommand{\\'"$KEY"'}' "$FILE" | head -1 \
                | sed -re 's/.*\{(.*)\}$/\1/; s/\\_/_/g'
}

######################################################################
# Read config from tex file and expand sub-variables
read_config() {
	local FILE=$1
	local KEY=$2
	local DATA VAL

	DATA=$(read_tex "$FILE" "$KEY")
	# shellcheck disable=SC1003,SC2076
	while [[ $DATA =~ '\' || $DATA =~ '#' ]] ; do
		KEY=$(sed -re 's/\\#/\\/; s/.*\\+([a-z]+).*/\1/' <<<"$DATA")
		VAL=$(read_tex "$FILE" "$KEY")
		# shellcheck disable=SC1003,SC2076
		[[ $VAL =~ '\' ]] && VAL="\\$VAL"
		DATA=$(sed -re "s/[\\]+$KEY/$VAL/g" <<<"$DATA")
	done
	echo "$DATA"
}
ARCH="$(read_config "$TEXFILE" "arch")"
if [[ -z $TARGET || $TARGET = "TBD" ]] ; then
	BOARD="$(read_config "$TEXFILE" "board")"
	BOARDFILE="$(grep '\\input{board' "$TEXFILE" \
		| sed -e '/%/d; s/\\board/'"$BOARD"'/; s/.*{//; s/}.*//').tex"
	TARGET="$(read_config "$BOARDFILE" "targetnick")"
fi

# Associate s_numbers with MODULE Session names
# Then copy lab solutions over and make appropriate subsitutions

most_of_the_work(){

grep -e CHAPS "$TEXFILE" \
    | grep -v "^%" \
    | sed -e s:'\\'subimport{CHAPS/::g \
    | sed -e s:/}{index}::g | \
    while read session ;  do \
    n=$((n+1)) ;
    if [[ "$TEXFILE" == "$APPENDICES" ]] ; then
	sdir=s_${a_from_num[$(($n-1))]}
    else
	nprint=$n
	[[ $n -lt 10 ]] && nprint=0"$n"
	sdir=s_"$nprint"
    fi
    mkdir -p SOLUTIONS/$sdir/EXAMPLES
    mkdir -p RESOURCES/$sdir
    LABS=labs
    if [[ -d $MODULES/$session/$TARGET/${COURSE}labs ]] ; then
	LABS="$TARGET/${COURSE}labs"
    elif [[ -d $MODULES/$session/$TARGET/labs ]] ; then
	LABS="$TARGET/labs"
    elif [[ -d $MODULES/$session/${COURSE}labs ]] ; then
	LABS="${COURSE}labs"
    fi
    echo LABS=$LABS
    if [ -d $MODULES/$session/$LABS ] ; then
#        echo -e "checking for broken links \n"
        pushd $MODULES/$session/$LABS > /dev/null
            find . -type l | while read f; do
                if [ ! -e "$f" ]; then
                    touch .broken
                    ls -l "$f"
                fi
            done
            if [ -f .broken ] ; then
                rm .broken
                echo -e "\nYOU HAVE BROKEN LINKS in $session/$LABS. Go figure. ^^^^^  \n"
                echo "I will *NOT*throw the SOLUTIONS away to prevent incomplete tarballs ..."
#                rm -r $THISDIR/SOLUTIONS/s_*
#                touch $THISDIR/SOLUTIONS/.broken
#                exit 1
            fi
        popd > /dev/null
	echo "doing $sdir $LABS"
	cp -aL $MODULES/$session/$LABS/* SOLUTIONS/$sdir 2> /dev/null
	for names in SOLUTIONS/$sdir/*.{c,h,cpp}
	do
	    [[ -f $names ]] && updatecsourcefile $names
	done
#	for names in $(find SOLUTIONS/$sdir/ -name "*.[sh,stp]")
	for names in SOLUTIONS/$sdir/*.{sh,stp}
	do
	    [[ -f $names ]] && updatescriptfile $names
	done
	pushd SOLUTIONS/$sdir > /dev/null
	for names in $(find . -name "*bz2" -or -name "*gz" -or -name "*xz" -or -name "*tar" -or -name "*mp4" -or -name "*iso" -or -name "*zip" )
	do
	    if [[ -f $names ]] ; then

		# no mp4 files in LFS2 courses		
		[[ $COURSE = *"LFS2"* ]] &&  [[ $names == *"mp4"* ]] && rm $names  && break

		LINKFILE="../../$MODULES/$session/$LABS/$names"
		SRCFILE="$(readlink -e $LINKFILE)"
 		hardlink_to_save_space $SRCFILE $names
		# do not move non soft linked files, that are small or should be
		[[ -L $LINKFILE ]] && mv $names ../../RESOURCES/$sdir
	    fi
	done
	popd > /dev/null
    fi
# a bizarre error in LFS201 has one mp4 leaking through
    rm SOLUTIONS/s_*/*.mp4 >& /dev/null
    echo "doing $sdir   EXAMPLES"
    cp -aL $MODULES/$session/*.{c,h,cpp,sh,stp,yaml,json,py} \
	SOLUTIONS/$sdir/EXAMPLES 2> /dev/null
    for names in SOLUTIONS/$sdir/EXAMPLES/*.{c,h,cpp} ; do
	[[ -f $names ]] && updatecsourcefile $names
    done
    for names in SOLUTIONS/$sdir/EXAMPLES/*.{sh,stp} ; do
	[[ -f $names ]] && updatescriptfile $names
    done
 # avoid duplicate names
######   THIS FAILS TO GET ALL IN LFD435, backing out for now
#######    edir=SOLUTIONS/$sdir/EXAMPLES
#######    for names in $edir/*
#######    do
#######	[[ -f $names ]] &&
#######	[[  "$(diff -s $names SOLUTIONS/$sdir | grep identical)" ]] \
#######	    && rc=$? && [[ $rc=0 ]] &&  rm  $names
#######    done
done

}

rm -rf SOLUTIONS/.broken
rm -rf SOLUTIONS/s_*
# might as well start RESOURCES up fresh,
# no need for license as components have their own
rm -rf RESOURCES/ ; mkdir RESOURCES

TEXFILE=$TEXFILE
most_of_the_work
TEXFILE=$APPENDICES
most_of_the_work

# THROW AWAY EMPTY SOLUTION and RESOURCES DIRECTORIES
rmdir SOLUTIONS/s_*/EXAMPLES 2> /dev/null
rmdir SOLUTIONS/s_* 2> /dev/null
rmdir RESOURCES/s_* 2> /dev/null
# THROWN AWAY README FILES
rm $POUNDREADMEFILE $READMEFILE

echo FINISHED making SOLUTIONS for $COURSE, VERSION $VERSION
