#!/bin/sh -e

BRANCH=sisyphus
TASKFS_MOUNT_POINT=/tasks

! [ -e $HOME/.config/repocop-tasktest.conf ] || . $HOME/.config/repocop-tasktest.conf

REPOCOP_TASKREPORT_DIR=${REPOCOP_TASKREPORT_DIR:-/var/ftp/pub/repocop/$BRANCH-tasktest/tasks}

# checks
if [ -z "$TASKFS_MOUNT_POINT" ] || ! [ -d "$TASKFS_MOUNT_POINT" ]; then
    echo "Fatal: TASK FS not found at $TASKFS_MOUNT_POINT"
    exit 1
fi

if [ -z "$REPOCOP_TASKREPORT_DIR" ] || ! [ -d "$REPOCOP_TASKREPORT_DIR" ]; then
    echo "Fatal: REPOCOP_TASKREPORT_DIR not found at $REPOCOP_TASKREPORT_DIR"
    exit 1
fi

if ! stat -t ${TASKFS_MOUNT_POINT}/[0-9]* >/dev/null 2>&1; then
    echo "${TASKFS_MOUNT_POINT} is empty. No tasks to test."
    exit 0
fi

test_task()
{
    local taskpath
    taskpath=$1
    [ -d "$taskpath" ] || return 0
    taskrepo=`cat "$taskpath/task/repo"`
    [ "$BRANCH" = "$taskrepo" ] || return 0
    taskstate=`cat "$taskpath/task/state"`
    [ -e "$taskpath/task/test-only" ] && tasktestonly=1 || tasktestonly=
    [ "$taskstate" = "EPERM" ] || ([ "$taskstate" = "DONE" ] && [ -n "$tasktestonly" ]) || return 0
    taskid=`basename "$taskpath"`
    tasktry=`cat "$taskpath/task/try"`
    if ! [ -d "$REPOCOP_TASKREPORT_DIR"/$taskid/$tasktry ]; then
	echo "testing: $taskid #$tasktry"
	if ! repocop-tasktest-test $taskpath; then
	    echo repocop-tasktest-test $taskpath failed
	    exit 1
	fi
    fi
    return 0
}

for taskpath in ${TASKFS_MOUNT_POINT}/[0-9]* ; do
    test_task "$taskpath"
done
