#!/bin/sh

# try to execute the build requests given.

LOCATION=/var/spool/common-lisp-controller

# did we get removed?

if [ ! -x /usr/bin/clc-send-command ] ; then 
 # we got removed. Clean the directory:
 find $LOCATION -xdev -type f -print0 | xargs --null rm --force
 exit 0
fi

# do not trust anything in that directory!

# first remove files with strange characters:

#find $LOCATION \( -name "*\\n*" -or -name "*\\r*" -or -name "*;*" \) -and -type f -print0 \
find $LOCATION \( -name \*\;\* -or -name \*$'\015'\* -or -name \*$'\012'\* \) -and -type f -print0 \
  | xargs --null rm --force

OLDFILE=""
while true ; do
 # find the oldest file:
 FILE="`find "$LOCATION" -type f -printf "%T@ %p\n" | sort -n | head -n 1 | cut -d ' ' -f 2 `"
 if [ ! -f "$FILE" ] ; then
   exit 0
 fi
 if [ "$FILE" = "$OLDFILE" ] ; then
  echo looping
  exit 1
 fi
 OLDFILE="$FILE"
 # carefully execute the command:
 /usr/bin/clc-send-command --quiet --force-connect recompile \
  "`head -n 1 $FILE | cut -d ' ' -f 1 | sed 's/[^-a-zA-Z0-9]*//g'`" \
  "`head -n 1 $FILE | cut -d ' ' -f 2 | sed 's/[^-a-zA-Z0-9]*//g'`" 
 # delete the duplicates, regardless if we could build:
 grep --recursive --fixed-strings --files-with-matches --null \
   "`head -n 1 $FILE | cut -d ' ' -f 1,2 | sed 's/[^-a-zA-Z0-9 ]*//g'`" ${LOCATION}/* | \
  xargs --null rm --force 
done

