#!/bin/zsh
#
# Find and list filenames for zia postings
#

function usage {
    cat 1>&2  << EOUSAGE
Usage:  $pgm [-/] [command]
 where command can be one of:
   last - show filename for just the last posting
   day - show filenames for last day with any postings
   month - the whole last month that had any
   all - all postings to this weblog
   default is just "last".
 and -/ means to disable the tilde back-substitution.
EOUSAGE
    exit 1
}

function tildefilter {
    # test that tildefilter is real
    # sed 's/\//----/g'
    # echo "s,$(eval echo ~),~,g"
    sed "s,$(eval echo ~),~,g"
}

pgm="$0"

#
# I tried doing it this weird way in order to preserve the tilde in the output.
#   blog='~/.bzero/zia'
#   cd `eval echo $blog`
# That worked, but made the "ls" commands at the end not work.
# So this time, I'll try filtering the output.
#
blog=~/.bzero/zia
cd $blog
# echo debug  blog directory $blog, pwd $(pwd)

cd data
blogdatapath="$blog/data"
# echo debug  blogdatapath $blogdatapath and pwd $(pwd)

year=$( ls -dr 2??? | head -1 )
if [ ! -d $year ] ; then
    echo Year $blogdatapath/$year not a directory.
    usage
fi

cd $year
yearpath="$blogdatapath/$year"
# echo debug  yearpath $yearpath and pwd $(pwd)

# This line sure would be cleaner if Phil had left leading
#  zeros on the months.
months=$( ls -d ? ?? | sort -n )
month=$( echo $months | tail -1 )

cd $month
monthpath="$yearpath/$month"
# echo debug  monthpath $monthpath and pwd $(pwd)

# Same trick...
days=$( ls -d ? ?? | sort -n )
day=$( echo $days | tail -1 )
# echo debug  days $days
# echo debug  day $day

cd $day
postings=$( ls | sort -n )
# echo debug  postings all is $postings
lastpost=$( echo $postings | tail -1 )
daypath="$monthpath/$day"
# echo debug  daypath $daypath and pwd $(pwd)

case "$1" in
 -/)  # Only option for now:  -/ disable the tildefilter.
      shift
      function tildefilter { cat ; }
esac
cmd="$1"
case "$cmd" in
 day)       # last day with any postings
	    # echo $daypath
	    cd $daypath
	    ls *.txt | sort -n | sed "s,^,$daypath/," | tildefilter
            ;;
 month)     # this month
	    # echo $monthpath
	    cd $monthpath
	    for day in ? ?? ; do
		cd $day
		ls *.txt | sort -n | sed "s,^,$monthpath/$day/," | tildefilter
		cd ..
	    done
            ;;
 all)       # Everything.
	    cd $blogdatapath
	    for year in ???? ; do
		cd $year
		for month in * ; do
		    cd $month
		    # echo all month $(pwd)
		    for day in * ; do
			cd $day
			ls *.txt | sort -n | sed "s,^,$(pwd)/," | tildefilter
			cd ..
		    done
		    cd ..
		done
		cd ..
	    done
            ;;
 ""|last)   # Last posting, or the default command.
	    echo $daypath/$lastpost | tildefilter
            ;;
 *)         # Bad command
	    usage
            ;;
esac
