#!/bin/sh

continuous_integration_mode=
[ "$1" = '--continuous' ] && continuous_integration_mode=--continuous
[ "$1" = '-c' ] && continuous_integration_mode=--continuous

set -e

. autorepo-config

lockfile=$AUTOREPO_HOME/autorepo-lock
unlock_workdir_safe() {
    if grep '^'$$'$' $lockfile >/dev/null 2>&1; then
	rm -rf $lockfile ||:
    fi
}
unlock_workdir_force() {
    rm -rf $lockfile ||:
}
lock_workdir() {
   echo $$ > $lockfile
}
unlock_workdir_trap() {
   unlock_workdir_safe
   exit
}

trap unlock_workdir_trap INT TERM EXIT

if [ -e $lockfile ]; then
    lockpid=`cat $lockfile`
    if ps ax | awk '{print $1}' | grep '^'$lockpid'$'; then
	echo autoports are locked. exiting ...
	exit 1
    else
	echo "WARNING: process is dead, but lock file exists. "
	cat $lockfile
	unlock_workdir_force
    fi
fi

lock_workdir

#rm -rf $AUTOREPO_HOME/OUT
#autorepo-genrepo # should be run once per repository
set -v
autorepo-rm-out-dups > $AUTOREPO_HOME/dups.log 2>&1
[ -s $AUTOREPO_HOME/dups.log ] && cat $AUTOREPO_HOME/dups.log || rm -f cat $AUTOREPO_HOME/dups.log
autorepo-rotate-bad-ugly
autorepo-mass-build $continuous_integration_mode
autorepo-merge-good
autorepo-purge -q > $AUTOREPO_HOME/purge.log
autorepo-relink-srpms
autorepo-make-filelists
autorepo-genrepo
if [ -s $AUTOREPO_HOME/purge.log ]; then cat $AUTOREPO_HOME/purge.log; else rm -f $AUTOREPO_HOME/purge.log; fi
autorepo-repo-unmets

unlock_workdir_safe
