#!/bin/ksh

unset IFS

TAG_BASEDIR=`/twc/bin/db_exp -f c_adtag_directory -s dif /twc/dif/wxl_dif`

cd $TAG_BASEDIR

FILELIST=`ls */remove.sh 2>/dev/null`

rm $TAG_BASEDIR/cleanup_obsolete_tags.log

for file in $FILELIST
do
  ##############################################################################
  # Compare the current time to the time the tag is set to expire.
  # Only remove the tag if current time is past expire time.
  #
  CURRENT_TIME=`amtime1970`

  # Get the directory name
  IFS=/
  echo "$file" | read dirname filename
  IFS=  

  EXPIRE_TIME="-1"
  # If the expiration file is not there, then expire the tag.
  # { Is this what we want? }
  if [[ -f $dirname/expiration ]]
  then
    exec 0< $dirname/expiration
    read EXPIRE_TIME
  fi
  if [[ "x$EXPIRE_TIME" = "x" ]]
  then
    EXPIRE_TIME="-1"
  fi
  ##############################################################################
  
  if (( $CURRENT_TIME >= $EXPIRE_TIME ))
  then
    # Execute the remove script
    echo "Tag $dirname expired (current time $CURRENT_TIME >= expiration time $EXPIRE_TIME)." >> $TAG_BASEDIR/cleanup_obsolete_tags.log
    echo "Removing..."
    "$file" >> $TAG_BASEDIR/cleanup_obsolete_tags.log
    echo "Completed $file for removal of $dirname" >> $TAG_BASEDIR/cleanup_obsolete_tags.log
    # Now, remove the directory and everything below it.
    rm -rf "$dirname"
    echo "Tag $dirname removed." >> $TAG_BASEDIR/cleanup_obsolete_tags.log
  else
    echo "Tag $dirname not removed since current time ($CURRENT_TIME) < expiration time ($EXPIRE_TIME)" >> $TAG_BASEDIR/cleanup_obsolete_tags.log
  fi
done
