#!/usr/bin/env bash

I_TITLE=${I_TITLE-$(basename $(pwd))}
I_CSS=${I_CSS-index.css}
I_JS=${I_JS-index.js}
I_LSFLAGS=${I_LSFLAGS-"-A"}

item () {
    FULLPATH=$1
    if [ -d $1 ]; then
        EXTN=dir
        FULLPATH="${1}/"
    else
        BASENAME=$(basename $1)
        case $BASENAME in
            .*) EXTN=none;;
            *.*) EXTN=${1##*.};;
            *) EXTN=none;;
        esac
    fi

    case $OSTYPE in
        *darwin*|*bsd*)
            LAST_MODIFIED=$(stat -f "%m" $FULLPATH | date +"%b %d &apos;%y") ;;
        *linux*|*solaris*|*msys*)
            LAST_MODIFIED=$(date -r $FULLPATH +"%b %d &apos;%y" ) ;;
    esac
    echo "<p class=\"extn-$EXTN\">"
    echo "  <a href=\"$FULLPATH\">$FULLPATH</a>"
    echo "  <span class=\"date\">$LAST_MODIFIED</span>"
    echo "</p>"
}

header () {
    echo '<!DOCTYPE html>'
    echo '<meta name="viewport" content="width=device-width, initial-scale=1"/>'
    echo "<title>$I_TITLE</title>"
    echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$I_CSS\"></link>"
    echo "<script type=\"text/javascript\" src=\"$I_JS\"></script>"
    echo "<h1>$I_TITLE</h1>"
}

body () {
    if [ -z $I_DOTDOT ]; then
        echo '<p class="dir"><a href="../">..</a></p>'
    fi

    for FNAME in $(ls $I_LSFLAGS | grep -v ^.indexme$ | grep -v ^index.html$); do
        item "$FNAME";
    done
}

for TGT in $(find ~ -name .indexme); do
    TGT_DIR=$(dirname $TGT)
    cd $TGT_DIR
    pwd
    header > index.html
    body >> index.html
done
