#!/bin/bash

# Title......: mkindex
# Description: create index.html for files
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Thu 20 Feb 2025 09:49:13 AM CST
#----------------------------------


# Sections: Changes variables functions setup main
# use '#' in vi/vim to jump to word under cursor

: ' Changes
Fri Feb 23 2024 changed the name to mkindex
Sat Feb 10 2024 Added version() to display version and changes
Sun Feb 04 2024 Cleaned up a little on the News section with single test
Fri Jan 26 2024 Code clean up and new debug settings
Thu Dec 21 2023 Added creation of include.html for use with iframes
Sun Oct 15 2023 Added tech news to news bottom of news page
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
[ "$DEBUG" == 1 ] && echo "---Variables---" && set -x 
INCLUDE=/var/www/include                  # location of my html headers and footer
BASE=/var/www
PDIR="$(cd ..;basename $PWD)"
DIR="$(basename $PWD)"
NAME=${0##*/}                       # name of the script
PDOCOPT="--from=markdown+emoji+lists_without_preceding_blankline+autolink_bare_uris+grid_tables"
[[ $(pwd) == *"$(date +%a|tr [A-Z] [a-z])"* ]] && LOC="NEWS"

if [ -f .conf ]                    # check for local config file for settings
then
    source .conf
else                               # default values
    HEADER="$INCLUDE/media_header.html"
    FOOTER="$INCLUDE/footer.html"
    TITLE="$(echo ${PDIR}/${DIR}|cut -d'.' -f1|tr '-' ' '|sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')"
    SORT="-t"
    BACKGROUND=""
fi
[ "$#" -gt 0 ] && OPTIONS="$*"      # if OPTIONS is set in .conf, it will use them as long as none are passed
[ "$DEBUG" == 1 ] && set +x && read -p "${N}-Continue-" -n 1 x

# functions
#----------------------------------

bl(){ ## write a blank line
    # Use: bl
    [ "$DEBUG" == "1" ] && set -x
    echo "" 
}

html(){ ## mark up code
    vim -f +"syn on" +"colorscheme termschool" +"set nonu" +"set foldenable!" +"set nospell" +"run! syntax/2html.vim" +"wq" +"q" $1
}

log(){ ## creates a basic log entry $LOG must be defined
    # Use: log {entry}  
    [ "$DEBUG" == "1" ] && set -x
    logger -i -t "Files" "$*"
}

pause(){ ## simple pause routine
    # Use: pause  {optional number of seconds} or "-nt" for no time out 
    [ "$DEBUG" == "1" ] && set -x
    [ "$1" == "-nt" ] && TMOUT="" && shift
    echo "$BY";
    if [ $# -gt 0 ]
    then
        read -t $1 -r -p "${C}Hit any key (${BY}$1${C} second timeout)${N}" -n 1 FOO;
    else
        read -r -p "${C}Hit any key${N}" -n 1 FOO;
    fi;
    bl
}

xtitle(){ ## set window title
    # Use: xtitle "Text to display"
    printf "\033]0;%s\007" "$*"
}

version(){ ## display version and change history
    grep -E '^# Updated' $0
    bl
    sed -n "/' Changes/,/^ *$/p" <$0 |grep  -E -v 'sed -n|exit 0|}'
    exit 0
}

compile(){ ## Compile

if [ "$LOC" == "NEWS" ] # Add Oped if any mp4 are here
then
    rss2md -o >>index.md
    bl >>index.md
fi

## tail end
if [ -f tail.md ] # Add if here, else do a random quote!
then
    bl >>index.md
    cat tail.md >>index.md
    bl >>index.md
fi

if [ "$LOC" == "NEWS" ] # Add tech news to bottom
then
    rss2md -t >>"index.md"
    bl >>index.md
fi
if [ $(basename $PWD) != "gif-files" ]
then
bl >>index.md
echo ":scroll:">>index.md
echo "$(quote -w)" >>index.md
bl >>index.md
fi

CURRENT=$(pwd)
if [ $(basename $PWD) != "gif-files" ]
then
    echo "[🔝](#)" >>index.md
    echo "<hr>" >>index.md
    bl >>index.md
fi
echo "Updated:  $(date)">>index.md
pandoc "$PDOCOPT" "index.md" -o $$.html   # convert markdown to html
cp $$.html include.html        # used in iframes, no menus
cat "$HEADER" >"index.html"    # create new html file with header
cat $$.html >>"index.html"     # add new content
cat "$FOOTER" >>"index.html"   # add footer
rm $$.html                     # clean up
log "Processed: $PWD"          # update system log
exit                           # script ends after a compile
}

# setup
#----------------------------------

# this provides a quick way to edit all my scripts on the fly
if [ "$1" == "-E" ]
then
    vim $0
    sed -i -e "7s/.*/# Updated....: $(date)/" $0
    html $0
    cp $0 /var/www/unix
    mv $0.html /var/www/unix
    exit
fi

# display help if needed
if [ "$1" == "-h" ] || [ "$1" == "--help" ]
then
fmt -s -w $(tput cols) <<END  # formats out to display width 
$NAME -conf

Generate an index.html file from all files in a directory.

-conf {name}# display default .conf format or $INCLUDE/{file}
-c          # Check the files in current directory for links in $BASE Markdown files
-d          # directories only, skip files
-f          # files only, skip directories
-l          # List all header files in $INCLUDE
-L          # List all conf files in $INCLUDE
-r          # Recurse into subdirectories (will automaticly do it if missing index.html)

.bold       # Any file listed in this file will be bold, and italic.
.conf       # Settings for: HTML header (menu), footer, title, and sorting.
.desc       # one line description of directory used if set in parent listing
header.md   # If found it will parse the markdown into the index.html at top.
head.md     # If found it will parse the markdown into the index.html at top after header.
tail.md     # If found it will parse the markdown into the index.html at bottom.

Note: "-d" or "-f" will have not impact on the header.md or tail.md, if you do not want them they must be removed. 

## Conf file format
$($0 -conf)

END
exit
fi

# display version and change history
if [ "$1" == "-v" ] || [ "$1" == "--version" ]
then
    version
fi


# listing of required apps
#--------------------------- 
command -v bash >/dev/null || sudo apt install bash -qyy
#command -v site >/dev/null || exit 1 
command -v pandoc >/dev/null || sudo apt install pandoc -yyq

# create .conf file
#--------------------------- 
if [[ "$1" == "-conf" ]] && [[ -f "$INCLUDE/$2" ]]
then
    cat "$INCLUDE/$2"
    exit
fi

if [ "$1" == "-conf" ]
then
echo '
# Sort options:
#   extension: -X
#   time: -t
#   reverse: -r
#   size: -S
#--------------------------------------
HEADER="$INCLUDE/media_header.html"   # list headers choices: files -l
FOOTER="$INCLUDE/footer.html"
TITLE="CRN/something" # page title
SORT=""
BACKGROUND=""         # image for background of HTML (will override header setting)
OPTIONS=""            # set default options
'
exit
fi

# file check
#--------------------------- 
if [ "$1" == "-c" ]
then
    for FILE in $(ls|egrep -v 'index|header|tail') # skip matching files
    do
        [ -d $FILE ] && continue  # ignore directories
        cd "$BASE"
        for SOURCE in $(find . -name '*.md' -print|egrep -v "$DIR|version")
        do
            if [ $(grep -c "$FILE $SOURCE")  -gt 0 ]
            then
                echo "$FILE: $SOURCE $(grep -c $FILE $SOURCE)"
            fi
        done
        cd - >/dev/null
    done
    exit
fi

# list headers
#--------------------------- 
# if you want a copy of the ones I use, email me.
if [ "$1" == "-l" ]
then
    cd $INCLUDE
    ls ${SORT} *header*
    cd - >/dev/null
    exit
fi

# list conf files
#--------------------------- 
# if you was a copy of the ones I use, email me.
if [ "$1" == "-L" ]
then
    cd $INCLUDE
    ls ${SORT} *conf*
    cd - >/dev/null
    exit
fi

# directory check
[[ "$(pwd)" != *"include"* ]] && echo "$NAME: directory error" && exit 1 # only run under include
[[ "$(pwd)" == "$INCLUDE" ]] && echo "$NAME: directory error" && exit 1  # but not in it

# main
#--------------------------- 
[ "$DEBUG" == 1 ] && echo "---Functions---" && typeset -F && read -p "${N}-Continue-" -n 1 x
[ "$DEBUG" == 1 ] && echo "---Main---" && set -x

## top 

log "Creating new index"
bl >index.md         # start a new file each run
[ ! -z "$BACKGROUND" ] && echo "<style> body { background-image: url($BACKGROUND); } </style>" >index.md  # if a background is set start with that
echo "# $TITLE" >>index.md
bl >>index.md
if [ "$LOC" == "NEWS" ]
then
    log "News folder found: setting header"
    echo "<div style=\"text-align: center;\">">>index.md
    echo "## $(date "+%A %B %e, %Y")">>index.md
    echo "</div>">>index.md
fi
[ -f header.md ] && cat header.md >>index.md
bl >>index.md
[ -f .bold ] && bl >>index.md && echo "___Bold Italics items are recommended___" >>index.md && bl >>index.md
echo "<hr class=\"two\">"  >>index.md
bl >>index.md
if [ "$LOC" == "NEWS" ] # Add daily Proverb to today's clip listing
then
    echo -n "<div style=\"text-align: center;font-size: x-large;\">[:scroll: Proverb $(date "+%e")](/ab/ot/20-proverbs/#prv-$(date +%-e)){target="blank"}">>index.md
    echo " [📚 Morning And Evening](/include/faith/morning-and-evening.pdf#view=FitH&nameddest=Morning, $(date "+%B %-e")){target="blank"}</div>">>index.md
    bl >>index.md
    if [ -f head.md ]
    then
        cat head.md >>index.md
        bl >>index.md
        /home/mitch/bin/rss2md >>index.md
        bl >>index.md
    fi
else
    [ -f head.md ] && cat head.md >>index.md
    bl >>index.md
fi

## check for additional directories
for DIRS in $(\ls -d */ 2>/dev/null)
do
    [[ "$OPTIONS" == *"-f"* ]] && break
    DIRN=$(echo $DIRS|cut -d'.' -f1|tr '-' ' '|sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')
    if [[ $DIRN == *"$(date +%a)"* ]] || [[ "$DIRN" == *"$(date +%b)"* ]]
    then
        echo "- [📂 ___${DIRN}___](${DIRS}) $([ -f "$DIRS.desc" ] && cat "$DIRS.desc")" >>index.md
    else
        echo "- [📂 ${DIRN}](${DIRS}) $([ -f "$DIRS.desc" ] && cat "$DIRS.desc")" >>index.md
        if [ $(ls -d ${DIRS}*/ 2>/dev/null| wc -l) -gt 0 ]
        then
            for SUBD in $(\ls -d ${DIRS}*/)
            do
                SUBN=$(echo $(basename $SUBD)|cut -d'.' -f1|tr '-' ' '|sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')
                if [[ "$SUBD" == *"$(date +%b|tr [A-Z] [a-z])"* ]] || [[ "$SUBD" == *"$(date +%a|tr [A-Z] [a-z] )"* ]]
                then
                    echo "  - [📂 ___${SUBN}___](${SUBD}) $([ -f "$SUBD.desc" ] && cat "$SUBD.desc")" >>index.md
                else
                    echo "  - [📂 ${SUBN}](${SUBD}) $([ -f "$SUBD.desc" ] && cat "$SUBD.desc")" >>index.md
                fi
            done
        fi
    fi
    if [ ! -f "${DIRS}index.html" ] || [[ "$1" == *"-r"* ]]
    then
        cd ${DIRS}
        $0 -n
        cd -
    fi
done
[ -n "$DIRS" ] && bl >>index.md && echo "---" >>index.md && bl >>index.md

[[ "$OPTIONS" == *"-d"* ]] && compile

## Get newest and place it at the top, for main directory.
if [[ "$OPTIONS" != *"-n"* ]] && [ $(ls *mp4 2>/dev/null|wc -l) -gt 0 ]
then
    NEW=$(find . -type f -name '*mp4' -printf '%C@ %p\n' | sort -n | tail -1 | cut -f2- -d" ")
    NEWF=${NEW##*/}         # name of the file
    if [ -f header.md ]
    then
        if [ $(grep -c "$NEW" header.md) -lt 1 ]
        then
            [ ! -f .skip ] && pi $NEWF >>index.md
            [ ! -f .skip ] && echo "<HR>" >>index.md
        fi
    else
        [ ! -f .skip ] && pi $NEWF >>index.md
        [ ! -f .skip ] && echo "<HR>" >>index.md
    fi
fi

## under construction (what to display in an empty directory)
if [ "$1" == "-u" ]
then
    cp ~/Pictures/under-construction-sign.png .  # You will need to change this to a place/pic of yours
else
    [ -f under-construction-sign.png ] && \rm under-construction-sign.png
fi

X=Y
## main loop
for FILE in $(ls ${SORT}|egrep -v 'index|header|tail|head|include')
do
    [ -d "$FILE" ] && continue # skip if it's a directory
    [ "$FILE" = "$NEWF" ] && continue
    if [ -f header.md ]
    then
        [ $(grep -c "$FILE" header.md) -gt 0 ] && continue
    fi
    if [ -f head.md ]
    then
        [ $(grep -c "$FILE" head.md) -gt 0 ] && continue
    fi
    if [ -f tail.md ]
    then
        [ $(grep -c "$FILE" tail.md) -gt 0 ] && continue
    fi
    echo -ne "\033[2K" # clear to the beginning of line
    echo -ne "\r$FILE" # move cursor to beginning of line, print file, no new line  ;)
    EXT="${FILE##*.}"
    NAME=$(echo $FILE|cut -d'.' -f1|sed -e 's/[-_]/ /g' -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')

    case $EXT in
        mp4|m4v| webm|mkv) # video to play
            bl >>index.md
            pi $FILE >>index.md
            bl >>index.md
            echo "[🔝](#) ">>index.md
            echo "<HR>>">>index.md
            ;;
        bmp|webp|jpg|jpeg|png|gif) # Pic
            bl >>index.md
            FILENAME="${FILE%.*}"
            if [ $(ls $FILENAME.* |wc -l) -lt 2 ]
            then
                pi $FILE |tr -d '\n' >>index.md
            fi
            ;;
        md) # markdown
            FILENAME="${FILE%.*}"
            if [ $(ls $FILENAME.* |wc -l) -lt 2 ]
            then
                mkln $FILE >>index.md
            fi
            ;;
        *) # fallback
            mkln $FILE >>index.md
            ;;
    esac
done

compile