#!/bin/sh
#
# database-statistics-sqlite
# Collects statistics for an OpenVAS Manager SQLite database
#
# Copyright (C) 2014  Greenbone Networks GmbH
#
# Authors:
#   Michael Wiegand <michael.wiegand@greenbone.net>
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# SCRIPT_NAME is the name the scripts will use to identify itself and to mark
# log messages.
SCRIPT_NAME="database-statistics-sqlite"

# LOG_CMD defines the command to use for logging. To have logger log to stderr
# as well as syslog, add "-s" here.
LOG_CMD="logger -t $SCRIPT_NAME"

log_write () {
  $LOG_CMD -p daemon.notice $1
}

if [ $# -ne 1 ]
then
  echo "Please provide the filename of the SQLite database to check:"
  echo "  $0 tasks.db"
  exit 1
fi

SQLITE3="sqlite3 -noheader -bail"
DATABASE="$1"

UNUSED_PAGES_COUNT=$($SQLITE3 "$DATABASE" "PRAGMA freelist_count;")

SUPERFLUOUS_ITG_RESULT_COUNT=$($SQLITE3 "$DATABASE" "SELECT COUNT() FROM results WHERE nvt = '1.3.6.1.4.1.25623.1.0.94000' AND port = 'general/IT-Grundschutz' AND ROWID NOT IN (SELECT ROWID FROM results AS outer_results WHERE length (description) = (SELECT max (length (description)) FROM results WHERE report = outer_results.report AND host = outer_results.host AND nvt = '1.3.6.1.4.1.25623.1.0.94000' AND port = 'general/IT-Grundschutz') AND nvt = '1.3.6.1.4.1.25623.1.0.94000' AND port = 'general/IT-Grundschutz' GROUP BY report, host);")

SUPERFLUOUS_OPEN_PORT_RESULT_COUNT=$($SQLITE3 "$DATABASE" "SELECT COUNT() FROM results WHERE nvt = '0';");

OLD_STYLE_RESULT_LOCATION_COUNT=$($SQLITE3 "$DATABASE" "SELECT COUNT() FROM results WHERE port LIKE '%)';");

DUPLICATE_CONFIG_PREFERENCES_COUNT=$($SQLITE3 "$DATABASE" "SELECT COUNT () FROM (SELECT config, type, name, value FROM config_preferences GROUP BY config, type, name, value HAVING COUNT() > 1);");

log_write "Unused pages: $UNUSED_PAGES_COUNT"

log_write "Superfluous ITG results: $SUPERFLUOUS_ITG_RESULT_COUNT"

log_write "Superfluous 'Open Port' results: $SUPERFLUOUS_OPEN_PORT_RESULT_COUNT"

log_write "Old style result locations: $OLD_STYLE_RESULT_LOCATION_COUNT"

log_write "Duplicate config preferences: $DUPLICATE_CONFIG_PREFERENCES_COUNT"

exit 0
