#!/bin/sh
######################################################################
# phlogger - Generate gopher log (phlog) gophermap
# Created 2009-12-3 by David Meyeri <[email protected]>.
######################################################################

# Identification #####################################################

PROGRAM='phlogger'
VERSION=0.0
COPYRIGHT='Copyright (C) 2009 David Meyer'
DESCRIPTION='Generate gopher log (phlog) gophermap.'
USAGE="Usage: $0 [-hV] [-n NUM] [-s SEL] [DIR]"
CONTACT='David Meyer <[email protected]>'

# Initialize environment #############################################

IFS="
"
PATH=/bin:/usr/bin

# Arguments ##########################################################

while getopts Vhn:s: option
do      case $option in
       n )     NUM=$OPTARG
               ;;
       s )     SEL=$OPTARG
               ;;
       V )     echo "$PROGRAM $VERSION"
               echo $COPYRIGHT
               exit 0
               ;;
       h )     cat << ENDHELP
$USAGE

$DESCRIPTION
DIR [=/ftp/user/$USER] is phlog root directory.

Options:
       -n NUM
               Display links and summaries of NUM most recently
               added or changed files.
       -s SEL
               Gopher selector SEL corresponding to <dir>
       -V      Display version number
       -h      Display this help message

Report bugs to $CONTACT.
ENDHELP
               exit 0
               ;;
       * )     echo $USAGE >&2
               exit 1
               ;;
       esac
done

shift $(( $OPTIND-1 ))

DIR=$1

# Functions ##########################################################

ftitle() {
       bn=$(basename $1)
       case $bn in
       *.txt | *.org )
               title=$(head -n 1 $1)
               ;;
       *.html | *.htm )
               title=$(grep -i "\<title\>" $1 | sed -e "s;</*[tT][iI][tT][lL][eE]>;;g")
               ;;
       * )
               title=$bn
               ;;
       esac
       echo $title
}

# Main driver ########################################################

owd=$PWD
cd $DIR

#if [ -f gophermap ]; then
#       cp gophermap gophermap~
#fi
#
#if [ -f .title ]; then
#       cat .title >gophermap
#fi
#
#if [ -f .phloghead ]; then
#       cat .phloghead >>gophermap
#fi

# Can I DESELECT hidden files in find?
ls -lt $(find . -type f) |\
while read p lc o g s dt1 dt2 dt3 fn; do
       ft=$(ftitle $fn)
       loc=$(basename $(dirname $fn))
       echo "0$dt1 $dt2 $dt3 $ft [$loc]        $SEL${fn%\./*}"
done

cd $owd

exit 0
#-rwxrwxrwx    1 root     root         1751 Dec  8 19:28 phlupd