#!/bin/bash

# Copyright: 2012 Collabora ltd.
# Author: Cosimo Alfarano <cosimo.alfarano@collabora.co.uk>

# Run all tests, mainly to be user under Lava, with a custom parser

# a list of .sh which are not actually a test, so we can silently ignore
NOT_TESTS="env_check.sh syscall_sysctl.sh"
# test that we need to skip, and let LAVA know about it
SKIP_TESTS=""

# I'm not sure what this does but the idea of doing pivot_root on a running
# system is terrifying, so I'm not surprised if it doesn't work
SKIP_TESTS="${SKIP_TESTS} pivot_root.sh"

# "ERROR: tmpdir '/tmp/...' is of type tmpfs; can't mount a swapfile on it"
SKIP_TESTS="${SKIP_TESTS} swap.sh"

PREFIX=/usr/lib/apparmor/tests
let num_failed=0

if [ "`whoami`" != "root" ]; then
    exec sudo -E $0
fi

export RESULTDIR=""
unset VERBOSE
RETAIN=-r

get_only_results_dir() {
	tail -1 | sed "s/Files retained in:.\(.*\)/\1/g"
}

cleanup() {
  rm -f $TMP
}

cd "$PREFIX"

TMP=`tempfile`
for TEST in ${PREFIX}/*.sh; do
  unset skip
  for AVOID_TEST in ${SKIP_TESTS}; do
    if [ "`basename ${TEST} .sh`" == "`basename ${AVOID_TEST} .sh`" ]; then
      echo ${TEST}: SKIP -
      skip=true
    fi
  done
  for AVOID_TEST in ${NOT_TESTS}; do
    if [ "`basename ${TEST} .sh`" == "`basename ${AVOID_TEST} .sh`" ]; then
      # we don't need to notify LAVA about this skip.
      skip=true
    fi
  done
  test -n "$skip" && continue

  bash ${TEST} ${RETAIN} > $TMP 2>&1
  OUTCOME=$?
  RESULTDIR=$(cat $TMP | get_only_results_dir)

  if [ "$OUTCOME" != 0 ]; then
        echo
        echo "# ${TEST} output..."
        sed -e 's/^/# /' < $TMP
        echo ${TEST}: FAILED - $RESULTDIR
        echo "# exit status: $OUTCOME"
        echo
        let num_failed+=1
  else
        echo ${TEST}: PASSED - $RESULTDIR
  fi
done
cleanup
exit $num_failed
