#!/bin/sh
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

# The idea here is to run ansible_local.bash --tags daily
# and then use this to do the parsing and throwing errors based on the output.
# This way the ansible run can be free from erroring and this can be
# run repeatedly anytime outside of ansible to deal with the issues raised.
# It is also run at the end of ansible_local.bash --tags daily to raise the issues.

prog=`basename $0 .bash`
PREFIX=/usr/local
ROLE=toxcore
. /usr/locaal/etc/testforge/testforge.bash
TOXCORE_LOG_DIR=$PREFIX/var/log
[ -d $TOXCORE_LOG_DIR ] || mkdir -p $TOXCORE_LOG_DIR

MYID=`id -u`
[ $MYID -eq 0 ] || WARN $prog should be run as root $MYID

which ansifilter >/dev/null 2>&1  && ansifilter=ansifilter || ansifilter=cat

ly=daily
i=0
errs=0
warns=0
WLOG="$TOXCORE_LOG_DIR"/$ly/W$prog$$.log
ELOG="$TOXCORE_LOG_DIR"/$ly/E$prog$$.log

#?ols_make_testforge_logs $TOXCORE_LOG_DIR

find "$TOXCORE_LOG_DIR"/$ly/ -type f -name W${prog}*.log  -o -name E${prog}*.log -mtime +1 -delete


if virsh list | grep -q Whonix-Gateway ; then
  /usr/local/bin/toxcore_libvirt_test_ga.bash
fi

# -%d
if ls /var/log/libvirt/qemu/*.log 2>/dev/null ; then
  sudo grep ^`date +%Y-%m`.*warning /var/log/libvirt/qemu/*.log | tee -a $WLOG
fi

# FixMe missing
[ -x $PREFIX/bin/toxcore_libvirt_test_xml.bash ] && \
  $PREFIX/bin/toxcore_libvirt_test_xml.bash 2>&1 | grep WARN: >> $WLOG

if which virt-host-validate 2>/dev/null ; then
    [ -f $TOXCORE_LOG_DIR/daily/virt-host-validate.log ] || \
	sudo virt-host-validate > $TOXCORE_LOG_DIR/daily/virt-host-validate.log 2>&1
    b=`grep FAIL $TOXCORE_LOG_DIR/daily/virt-host-validate.log|wc -l|sed -e 's/ .*//'`
    [ $? -eq 0 -a -n "$b" -a $b -gt 0 ]
    b=`grep WARN $TOXCORE_LOG_DIR/daily/virt-host-validate.log|wc -l|sed -e 's/ .*//'`
    [ $? -eq 0 -a -n "$b" -a $b -gt 0 ] && \
	WARN $b WARN in $TOXCORE_LOG_DIR/$ly/virt-host-validate.log $warns | tee -a  $WLOG
fi

if /etc/init.d/libvirtd status ; then
  virsh list | grep '^ [0-9]' | while read id elt rest ; do
    [ $rest = running ] || continue
    virsh dumpxml $elt | grep org.qemu.guest_agent.0.*connected || \
      WARN org.qemu.guest_agent not connected for $elt |tee -a $WLOG
#      <target type='virtio' name='com.redhat.spice.0' state='connected'/>
#      <target type='virtio' name='org.qemu.guest_agent.0' state='connected'/>
  done
fi

warns=`grep -c WARN: "$WLOG"`
[ $warns -ne 0 ] && \
  WARN "$prog $ly $warns warnings in $WLOG"

errs=`grep -c ERROR: "$ELOG"`
[ $errs -ne 0 ] && \
  ERROR "$prog $ly $errs errors in $ELOG" && \
  exit -$errs

[ $warns -eq 0 -a $errs -eq 0 ] && \
    ols_clean_testforge_logs $TOXCORE_LOG_DIR && \
    INFO  "No $ly errors in $TOXCORE_LOG_DIR"

exit 0
