#!/usr/bin/env bash

# Generates a simple index of the current folder and subfolders creating
# a table of contents of all of the .md files contained within.

long_contents=$(find . | sort)

# replace the absolute path in all lines
contents=${long_contents//\.\//}

prev=""

echo "$contents" | while read -r line || [[ -n $line ]];
do
    # the line contains a file, or hidden dir
    if [[ $line == *"."* ]]; then
        # if the line is an md, not in the .zk dir, and not a dir
        if [[ $line == *".md"* && ! -d "$line" && $line != *".zk"* ]]; then
            # extract the name of the file
            name=$(echo "$line" | sed 's/.*\///' | sed 's/\.md//')
            # create the link
            name="[$name]($line)"
        else
            continue
        fi
    else
        # the folders are titles
        name=$(echo -e "\n## $line")
    fi

    # two titles in a row means empty folder.
    if [[ $prev == *"##"* && $name == *"##"* ]]; then
        prev=$name
        name=$(echo -e "Folder Empty.\n$prev")
    else
        prev=$name
    fi

    echo "$name"
done
