#!/bin/bash

set -e

force=no
if [ "$1" = "-f" ]
then
  force=yes
fi

DEBS=/srv/local-apt-repository
REPO=/var/lib/local-apt-repository

if ! test -d $DEBS
then
  # We still need ot create the files lest apt will complain
  > $REPO/Packages
  > $REPO/Sources

else

  # We want to cater for the possibility that something is added to $DEBS as we
  # run. In this case, we want to wait a bit restart. But lets bound this to 10 runs.

  for n in $(seq 0 10)
  do
    if [ "$force" = "yes" ] || ! test -e  $REPO/stamp || find $DEBS -newer $REPO/stamp | fgrep -q ''
    then
      # we need to rebuild

      # This is the second round alreay, lets wait a while
      if [ "$n" != "0" ]
      then
        sleep 30
      fi

      touch $REPO/stamp

      # Relative paths work better than absolute
      (cd $REPO
      dpkg-scanpackages -m ../../../$DEBS > $REPO/Packages
      dpkg-scansources ../../../$DEBS > $REPO/Sources
      )

      force=no
    fi
  done

fi

cat > $REPO/Release <<__END__
Description: Local repository created by local-apt-repository
Origin: local-apt-repository
Components: .
MD5Sum:
 $(md5sum $REPO/Packages|cut -d\  -f1) $(wc -c $REPO/Packages|cut -d\  -f1) Packages
 $(md5sum $REPO/Sources|cut -d\  -f1) $(wc -c $REPO/Sources|cut -d\  -f1) Sources
__END__

