#!/bin/bash

# Find and check links to Doxygen pages for all applications within a given directory

WM_PROJECT_DIR="/opt/openfoam6"

source "$WM_PROJECT_DIR/etc/bashrc"


# Temporary replace the default browser to avoid overloading the system
#     CONTROLDICT=$HOME/.OpenFOAM/controlDict
#
#     BROWSER=""
#
#     # TODO: Strings containing double-dashes seem not really welcome in Bash...
#     if [ -f $CONTROLDICT ]; then
#         BROWSER=$(foamDictionary -entry "Documentation.docBrowser" -value $CONTROLDICT)
#         foamDictionary -entry "Documentation.docBrowser" -set "linkchecker --check-extern --recursion-level=0" $CONTROLDICT
#
#     else
#         echo "Documentation{docBrowser linkchecker --check-extern --recursion-level=0;}" >> $CONTROLDICT
#     fi
#

DIRECTORY=$WM_PROJECT_DIR/applications/

REGEXP="EXE = \$(FOAM_APPBIN)/"

REGEXP_URL="Real URL"

FILELIST=$(find $DIRECTORY -name "files")
declare -p FILELIST > /dev/null 2>&1

APPLIST=()

E404LIST=()

for FILE in ${FILELIST[@]}; do
    APPLIST+=($(grep "$REGEXP" $FILE | sed "s|$REGEXP||"))
done

declare -p APPLIST > /dev/null 2>&1

echo "Found applications at $DIRECTORY:"
for APPLICATION in ${APPLIST[@]}; do

    # NOTE: Following applications are not compiled
    if [ $APPLICATION == "foamyHexMeshBackgroundMesh" ]; then
        continue;
    elif [ $APPLICATION == "foamyHexMeshSurfaceSimplify" ]; then
        continue;
    elif [ $APPLICATION == "cellSizeAndAlignmentGrid" ]; then
        continue;
    elif [ $APPLICATION == "ccm26ToFoam" ]; then
        continue;
    elif [ $APPLICATION == "foamToTecplot360" ]; then
        continue;
    fi

    echo "  $APPLICATION:"
    ERROR=0

    # Check for failures with "-doc" option
    DOC_MESSAGE=$($APPLICATION -doc | grep "Result")
    DOC_URL=$($APPLICATION -doc | grep "$REGEXP_URL")

    if [[ $DOC_MESSAGE = *"404"* ]]; then
        ERROR=1
        echo "    ERROR: doc-page address not found for application $APPLICATION at $DOC_URL"
     else
         echo "    -doc OK"
    fi

    # Check for failures with "-srcDoc" option
    SRCDOC_MESSAGE=$($APPLICATION -srcDoc | grep "Result")
    SRCDOC_URL=$($APPLICATION -srcDoc | grep "$REGEXP_URL")

    if [[ $SRCDOC_MESSAGE = *"404"* ]]; then
        ERROR=1
        echo "    ERROR: srcDoc-page address not found for application $APPLICATION at $SRCDOC_URL"
     else
         echo "    -srcDoc OK"
    fi

    if [ $ERROR != 0 ]; then
        E404LIST+=($(find $DIRECTORY -type f -name "$APPLICATION.*"))
    fi

done

declare -p E404LIST > /dev/null 2>&1

echo "Summary of Doxygen wrong-linked applications:"
for DOXYFAIL in ${E404LIST[@]}; do
    echo "    $DOXYFAIL"
done

# Restore default browser
# if [ "$BROWSER" != "" ]; then
#     foamDictionary -entry "Documentation.docBrowser" -set "$BROWSER" $CONTROLDICT
# else
#     foamDictionary -entry Documentation -remove $CONTROLDICT
# fi
