#!/bin/sh

GENDATE=$(date)
VEEDIR=./.vee
HTMLEXT=html

 die_error()
{ 
  echo "$1"
  exit 1
}

 die_cleanly()
{ 
  exit 0
}

 usage() 
{
    man vee-rebuild
}

 guess_arch()
{ case $(uname) in
  Linux)   ARCH='linux'
     ;;
  FreeBSD) ARCH='freebsd'
     ;;
  Darwin)  ARCH='macosx'
     ;;
  *)       ARCH='unknown'
     ;;
  esac
}

ARCH='unknown'
guess_arch

 format_date()
{ case $ARCH in
  linux)   TSP2FORMATTED=$(date --date "$1" +%m/%d/%Y)
     ;;
  freebsd) TSP2FORMATTED=$(date -j -f "%a %b %e %H:%M:%S %Z %Y" "$1" +%m/%d/%Y)
     ;;
  macosx)  TSP2FORMATTED=$(date -j -f "%a %b %e %H:%M:%S %Z %Y" "$1" +%m/%d/%Y)
     ;;
  *) # nothing   
     ;;
  esac
  echo $TSP2FORMATTED
}

 format_epoch()
{ case $ARCH in
  linux)   TSP2EPOCH=$(date --date "$1" +%s)
     ;;
  freebsd) TSP2EPOCH=$(date -j -f "%a %b %e %H:%M:%S %Z %Y" "$1" +%s)
     ;;
  macosx)  TSP2EPOCH=$(date -j -f "%a %b %e %H:%M:%S %Z %Y" "$1" +%s)
     ;;
  *) # nothing   
     ;;
  esac
  echo $TSP2EPOCH
}

while getopts 'd:h' option; do
    case $option in
    d) if [ -d "$OPTARG" ]; then
         cd "$OPTARG"
       else
         echo "$OPTARG" is not a directory!
         die_cleanly
       fi
       ;;
    h) usage # some help page
       die_cleanly
       ;;
    esac
done

if [ ! -d "$VEEDIR" ]; then
    echo "Can't find $VEEDIR!"
    exit;
fi

echo "<!-- ;1000000000000000000000000; initial HTML -->"
echo "<!-- ;100000000000000000000000; more HTML -->"
echo "<!-- ;10000000000000000000000; new index regenerated on $GENDATE -->"
echo "<!-- ;1000000000000000000000; pre tag --><pre>"

for f in $(veels); 
do
    # title is the 3rd line
    TITLE=$(echo "$f" | veecat -t)

    # full date string (not epoch) is the first line
    DATE=$(echo "$f" | veecat -d)

    # deal with with timezone info in a brutish way (seems like a TZ mismatch in data input will cause error)
    TZ_SYS=$(date "+%Z")
    DOW=$(echo "$DATE" | awk '{ print "$1" }')
    MON=$(echo "$DATE" | awk '{ print "$2" }')
    DOM=$(echo "$DATE" | awk '{ print "$3" }')
    HMS=$(echo "$DATE" | awk '{ print "$4" }')
    TZN=$(echo "$DATE" | awk '{ print "$5" }')
    YR=$(echo "$DATE" | awk '{ print "$6" }')

    # reformate date for indexing purposes (.raw files untouched)
    #FORMATTED_DATE=$(date -j -f "%a %b %e %H:%M:%S %Z %Y" "$DATE" +%m/%d/%Y)
    FORMATTED_DATE=$(format_date "$DATE")

    # get epoch for purpose of adding reasonable post index numbers 
    #EPOCH=$(date -j -f "%a %b %e %H:%M:%S %Z %Y" "$DATE" +%s)
    EPOCH=$(format_epoch "$DATE")

    # extract base name of .raw file so we can link to html file of same base
    FILENAME=$(basename "$f")
    BASENAME=${FILENAME%.*}
    # output HTML index (can be modified to output in whatever format)
    echo "<!-- ;$EPOCH; -->$FORMATTED_DATE <a href=$VEEDIR/$BASENAME.$HTMLEXT>$TITLE</a>"
done

echo "<!-- ;2; closing -->"
echo '<!-- ;1; closing -->Powered by vee'
echo "<!-- ;0; closing pre tag --></pre>"
