#!/bin/bash
set -e

# Copyright 2013,2014 Holger Levsen (holger@layer-acht.org)
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>


. /usr/share/piuparts/lib/read_config.sh
get_config_value MASTER global master-directory
BTS_STATS="$MASTER/bts_stats.txt"

# exit if master-directory doesn't exist or if devscripts package is not installed
test -n "$MASTER" || $(which bts) || exit 0
# "bts select" needs libsoap-lite-perl too
dpkg -l libsoap-lite-perl >/dev/null 2>&1 || exit 0

# only run once a day
TODAY=$(date +%Y%m%d)
if $(grep -q ^$TODAY $BTS_STATS 2>/dev/null) ; then
	exit 0
fi

# query bts
RC="severity:serious severity:grave severity:critical"
OTHER="severity:wishlist severity:minor severity:normal severity:important"
DONE_RC=$(bts select usertag:piuparts users:debian-qa@lists.debian.org status:done archive:both $RC 2>/dev/null|wc -l)
OPEN_RC=$(bts select usertag:piuparts users:debian-qa@lists.debian.org status:open status:forwarded $RC 2>/dev/null|wc -l)
DONE_OTHER=$(bts select usertag:piuparts users:debian-qa@lists.debian.org status:done archive:both $OTHER 2>/dev/null|wc -l)
OPEN_OTHER=$(bts select usertag:piuparts users:debian-qa@lists.debian.org status:open status:forwarded $OTHER 2>/dev/null|wc -l)

# test if both values are integers
if ! ( [[ $DONE_RC =~ ^-?[0-9]+$ ]] && [[ $OPEN_RC =~ ^-?[0-9]+$ ]] && [[ $DONE_OTHER =~ ^-?[0-9]+$ ]] && [[ $OPEN_OTHER =~ ^-?[0-9]+$ ]] ) ; then
	echo "Non-integer value detected, exiting."
	echo "DONE_RC: $DONE_RC OPEN_RC: $OPEN_RC"
	echo "DONE_OTHER: $DONE_OTHER OPEN_OTHER: $OPEN_OTHER"
	exit 1
fi

# init file if needed
if [ ! -f $BTS_STATS ] ; then
	echo "date, non-RC done, non-RC open, RC done, RC open" > $BTS_STATS

fi

# finally, write stats
echo "$TODAY, $DONE_OTHER, $OPEN_OTHER, $DONE_RC, $OPEN_RC" >> $BTS_STATS
