#!/usr/pkg/bin/bash
#
# Update timestamps on blog/gopher posts or post caches
#
# License GPLv3 or later by [email protected]
#
# Call with no args to force post timestamps back to those stored in
# cached copies.
# Call with -u to update the timestamp cache.
# Call with -f to specify a single file to update
# Call with -g to use gopher directories, rather than the default blog
# directories.
#
gflag=
uflag=
fflag=

while getopts 'guf:' OPTION
do
 case $OPTION in
     g)  gflag=1
         ;;
     u)  uflag=1
         ;;
     f)  fflag=1
         fval="$OPTARG"
         ;;
     ?) printf "Usage: %s [-g] [-u] [-f filename]\n" $(basename $0) >&2
 esac
done

shift $(($OPTIND - 1))

# Edit BLOGDIR and TSTAMPDIR to suit
if [ "$gflag" ]; then
   BLOGDIR="$HOME/gopher/dat"
   TSTAMPDIR="$HOME/.gtstamps"
else
   BLOGDIR="$HOME/html/motd/journal/entries"
   TSTAMPDIR="$HOME/.tstamps"
fi

if [ "$uflag" ]; then
   SRC="$BLOGDIR"
   DEST="$TSTAMPDIR"
else
   SRC="$TSTAMPDIR"
   DEST="$BLOGDIR"
fi

if [ "$fflag" ]; then
   if [ ! "$uflag" ]; then
       # We are changing the timestamp on just one blog post file
       # from the cached timestamp, so both must exist
       if [ \( -e "$SRC/$fval" \) -a \( -e "$DEST/$fval" \) ]; then
           echo "Running touch -r $SRC/$fval $DEST/$fval"
           touch -r $SRC/$fval $DEST/$fval
       else
           echo "Either $SRC/$fval or $DEST/$fval does not exist, aborting"
       fi
   else
       # We are changing the timestamp on the cache, from the real
       # post file. So only the post file need exist.
       if [ -e "$SRC/$fval" ]; then
           echo "Running touch -r $SRC/$fval $DEST/$fval"
           touch -r $SRC/$fval $DEST/$fval
       else
           echo "$SRC/$fval does not exist, aborting"
       fi
   fi
else
   # We didn't specify a file, so operate on all of the posts we can
   # find. Build a list of posts that we will use in the next step
   FILES=$(find $BLOGDIR -name '*txt' -print0 | xargs -0 | sed -e "s!$BLOGDIR/!!g")

   for POST in $FILES
   do
       if [ "$uflag" -a \( ! -e "$DEST/$POST" \) -a \( ! -d $(dirname $DEST/$POST) \) ]; then
           echo "Creating $(dirname $DEST/$POST)"
           mkdir -p $(dirname $DEST/$POST)
       fi
       echo "Running touch -r $SRC/$POST $DEST/$POST"
       touch -r $SRC/$POST $DEST/$POST
   done
fi