#!/usr/pkg/bin/bash
#
# Publish named file from staging dir to blog dir.
#
# Call with -u to update the timestamp cache for all posts at the same
# time.
# Call with -f to publish the named file
# Call with -g to use gopher directories, rather than the default blog
# directories
# Call with -o to force overwrite of an existing post.
#
# License GPLv3 or later by [email protected]
#
fflag=
uflag=
oflag=
gflag=

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

shift $(($OPTIND - 1))

# Edit BLOGDIR and POSTDIR to suit
if [ "$gflag" ]; then
   BLOGDIR="$HOME/gopher/dat"
   POSTDIR="$HOME/docs/phlog"
else
   BLOGDIR="$HOME/html/motd/journal/entries"
   POSTDIR="$HOME/docs/posts"
fi

if [ "$fflag" ]; then
   if [ ! -d $(dirname $BLOGDIR/$fval) ]; then
     echo "Creating $(dirname $BLOGDIR/$fval)"
     mkdir -p $(dirname $BLOGDIR/$fval)
     chmod 751 $(dirname $BLOGDIR/$fval)
   fi

   if [ -e "$BLOGDIR/$fval" ]; then
       if [ "$oflag" ]; then
           echo "Publishing $fval to $BLOGDIR, overwriting existing post as you requested..."
           cp -f $POSTDIR/$fval $BLOGDIR/$fval
           chmod 644 $BLOGDIR/$fval
       else
           echo "Post $BLOGDIR/$fval exists - use the overwrite flag (-o) to force overwrite of an existing post"
       fi
   else
       echo "Publishing $fval to $BLOGDIR/$fval..."
       cp $POSTDIR/$fval $BLOGDIR/$fval
       chmod 644 $BLOGDIR/$fval
   fi
fi

if [ "$uflag" ]; then
   g=''
   if [ "$gflag" ]; then
       g='-g'
   fi

   if [ "$fflag" ]; then
       echo "Updating the timestamp cache for $fval [$HOME/bin/upd $g -u -f $fval]..."
       $HOME/bin/upd $g -u -f $fval
   else
       echo "Updating all entries in the timestamp cache [$HOME/bin/upd $g -u]..."
       $HOME/bin/upd $g -u
   fi
fi