#!/usr/bin/sh
notdone=1
timeout=0
start=`date +%H%M%S`

### CHANGE THESE VARIABLES ###
form_name="num"
prefix="E"
prefix_len=1
field_len=9
##############################

count_file=$form_name".dat"
lock_file=$count_file".lck"

while [ $notdone -eq 1 ]
do
  if [ ! -f $lock_file ]
  then
    echo $$ > $lock_file
    notdone=0
  elif [ `cat $lock_file` -eq $$ ]
  then
    notdone=0
  else
    now=`date +%H%M%S`
    if [ `expr $now - $start` -gt 4 ]
    then
      notdone=0
      timeout=1
    fi    
  fi
done

if [ $timeout -eq 0 ]
then
  if [ ! -f $count_file ]
  then
    echo "0" > $count_file
  fi
  seq=`cat $count_file`
  seq=`expr $seq + 1`
  length=`echo "$seq" | wc -c | cut -c1-8`
  length=`expr $length - 1`
  length=`expr $field_len - $prefix_len - $length`
  count=0
  while [ $count -lt $length ]
  do
    seq="0"$seq
    count=`expr $count + 1`
  done 
  echo $seq > $count_file
  echo "Content-type: text/html"
  echo "Status: 302"
  echo "Location: http://www.auburn.edu/administration/business-finance/pdf/"$form_name"_auto.pdf?"$prefix$seq"\n\n"
  `rm -f $lock_file`
else
  echo "Content-type: text/html"
  echo "Status: 302"
  echo "Location: http://www.auburn.edu/administration/business-finance/formtime.html\n\n"
fi
