#!/bin/bash
OUTFILE="index.md"

if [ "x$1" = "x" -o ! -d "$1" ]; then
	exit 1
fi

if [ $# -eq 1 ]; then
	find "$1" -type d -printf '%P\n' | while read TDIR; do
		$0 "$1" "$TDIR"
	done
	exit 0
fi

# Check directory
INDIR="$1/$2"
if [ ! -d "$INDIR" ]; then
	exit 1
fi

# Whether already has valid index.md file
if [ -s "$INDIR/$OUTFILE" ]; then
	grep -q "Auto-index of" "$INDIR/$OUTFILE"
	if [ $? -ne 0 ]; then
		exit 0
	fi
fi

rawurlencode() {
  local encoded=""
  encoded="$(curl -s -o /dev/null -w %{url_effective} --get --data-urlencode "$1" "")"
  encoded="${encoded##/?}"
  encoded="${encoded//%2F//}"
  if [ "x$2" = "x1" ]; then
    T_URLENCODE_REPLY="${encoded//\//\\/}"
  else
    T_URLENCODE_REPLY="${encoded}"
  fi
}

OUTTMP=`mktemp /tmp/.gen-index-XXXXX`

PTITLE=`basename "$2"`
if [ "x$PTITLE" = "x" ]; then
	PTITLE="/"
fi
echo -e "\`\`\`\n\"title\": \"$PTITLE\"\n\`\`\`\n" > $OUTTMP

RELPATH="/$2"
echo -e "# Auto-index of '$RELPATH'\n\n| Name | Last Modified | Size | Type |\n| -------------------- | -------------------- | ---------- | -------- |" >> $OUTTMP

PDIR=`dirname "$2"`
if [ "x$PDIR" = "x" -o "x$PDIR" = "x." ]; then
	PDIR="/index.md"
else
	PDIR="/$PDIR/index.md"
fi
rawurlencode "${PDIR}"
echo "| [&#x21E7; [parent directory]](${T_URLENCODE_REPLY}) | | | |" >> $OUTTMP

if [ "x$2" = "x" ]; then
	RELPATH=""
fi

find $INDIR -mindepth 1 -maxdepth 1 -type d -printf "| [&#x1F4C1; %f]("$RELPATH"/%f/index.md) | %TY-%Tm-%Td %TH:%TM:%.2TS | %s | %M |\n"  | while read T_LINE; do
	T_PATH=`echo "$T_LINE" | sed -e 's/^.*\[&#x1F4C1; .*\](//' -e 's/) | .*$//'`
	rawurlencode "$T_PATH" 1
	echo "$T_LINE" | sed 's/](.*) | /]('${T_URLENCODE_REPLY}') | /' >> $OUTTMP
done

find $INDIR -maxdepth 1 -type f \( -iname \*.markdown -o -iname \*.md -a ! -name index.md \) -printf "| [&#x1F4D5; %f]("$RELPATH"/%f) | %TY-%Tm-%Td %TH:%TM:%.2TS | %s | %M |\n" | while read T_LINE; do
	T_PATH=`echo "$T_LINE" | sed -e 's/^.*\[&#x1F4D5; .*\](//' -e 's/) | .*$//'`
	rawurlencode "$T_PATH" 1
	echo "$T_LINE" | sed 's/](.*) | /]('${T_URLENCODE_REPLY}') | /' >> $OUTTMP
done

# whether need to overwrite index file
if [ -s "$INDIR/$OUTFILE" ]; then
	diff -q "$INDIR/$OUTFILE" $OUTTMP >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		exit 0
	fi
fi

echo "Generate index file: $INDIR/$OUTFILE"
cat $OUTTMP > "$INDIR/$OUTFILE"
rm -f $OUTTMP
