#!/bin/sh

# ad1810-autoindex - reimplementation of Apache's mod autoindex as a shell
#                      script
#
# No copyright is claimed.  This code is in the public domain; do with it
# what you wish. Author: 2008 Joost van Baal, 2018 Joost van Baal-Ilić

p=`pwd`
p=${p##*/}/

# colors in thttpd style
cat <<EOT
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Index of $p</title>
 </head>
 <body bgcolor=#99cc99" text=#000000" link="#2020ff" vlink="#4040cc">
  <h2>Index of $p</h2>
  <pre>
EOT

printf '<a href="index-size.html">%5s</a>  <a href="index-time.html">%-16s</a>  <a href="index.html">%s</a>' \
 size last-changed name
echo '  <hr>'

# this bare-bones implementation assumes no spaces in filenames
#
## ls -algGhF --time-style=long-iso "$@" | tail --lines=+2 | \
##  while read d d s d t f p l
##  # -rw-r--r-- 1 3.1K 2007-11-20 01:03 ad1810-tachod
##  do
##    F=`echo $f | sed 's{[*/=>@|]${{'`
##    printf "%5s  %s %s  <a href='%s'>%s</a> %s %s \n" $s $d $t "$F" "$f" $p "$l"
##  done


# $@: -S for size-ordered; -t for time-ordered
ls -algGhF --time-style=long-iso "$@" | tail --lines=+2 | \
 while read d d s d t r
 do
   p=
   R=`echo $r | sed 's{[*/=>@|]${{'`
   l=`echo $R | sed 's{^.*\ ->\ {{'`
   if test "$l" = "$R"
   then
     # no symlinks here
     l=
     f=$r
   else
     p='->'
     f=${R%% *}
   fi
   # displaying file with optional trailing * or @ would be nicer...
   #  101  2007-12-06 15:40     f   f      ->  l
   printf "%5s  %s %s  <a href='%s'>%s</a> %s %s \n" $s $d $t "$f" "$f" $p "$l"
 done

echo '  </pre>'
echo '  <hr>'
echo "generated by <a href='http://mdcc.cx/ad1810-autoindex'>ad1810-autoindex</a> on `hostname --fqdn` on `date`"
echo "<!-- REMOVE THIS COMMENT TO PREVENT UPDATES OF THIS FILE BY update-ad1810-autoindex -->"
echo ' </body>'
echo '</html>'





# TODO
# run it from cron

# check utf8 handling

# strip symlink path: security.  use e.g. foo -> .../bar

# music@nagy:~/200801/Amy_Winehouse/Frank% ~joostvb/arch/ad1810-stuff/scripts/ad1810-autoindex > index.html
# music@nagy:~/200801/Amy_Winehouse/Frank% ~joostvb/arch/ad1810-stuff/scripts/ad1810-autoindex -S > index-size.html 
# music@nagy:~/200801/Amy_Winehouse/Frank% ~joostvb/arch/ad1810-stuff/scripts/ad1810-autoindex -t > index-time.html
#
# index@nagy:~music/200801-index% update-ad1810-autoindex 
