#!/bin/bash

# $1 : package filename
# $2 : sum of delta size to go from this package to the database one
cleanup() {
  grep "${1}$" ${dir}/deltas | while read delta md5sum dsize spkg tpkg
  do
    if cleanup ${spkg} $(( ${2} + ${dsize} ))
    then
      echo "${delta} ${md5sum} ${dsize} ${spkg} ${tpkg}" \
       >> ${dir}/cdeltas
    fi
  done
  [ ${2} -gt ${quota} ] && return 1
  if [ ${2} -eq 0 ]
  then
    rm -f ${dir}/deltas
    [ -f ${dir}/cdeltas ] mv -f ${dir}/cdeltas ${dir}/deltas
  fi
  return 0
}

# list contents of repo from the root of it
ls -1 | while read dir
do
	if [ ! -f ${dir}/desc -o ! -f ${dir}/deltas ]
	then
		continue
	fi
	filename=$(grep -A1 FILENAME ${dir}/desc | tail -n1)
	filesize=$(grep -A1 CSIZE ${dir}/desc | tail -n1)
	quota=$(( ${filesize} * 7 / 10 ))
	cleanup ${filename} 0
done
