#!/bin/sh
#
# OpenVAS
# $Id$
# Description: Update Port Names data.
#
# Authors:
# Hani Benhabiles <hani.benhabiles@greenbone.net>
#
# Copyright:
# Copyright (C) 2013 Greenbone Networks GmbH
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA.

POSTGRES=0
if [ "SQLITE3" = "POSTGRESQL" ]; then
  POSTGRES=1
fi

do_help () {
  echo "Update port names data from a port names XML file.\n";
  echo "Currently supports the official IANA Services Names list.";
  echo "In order to update the DB, download the port names list and";
  echo "provide its path as an argument to this script.";
  echo " $ wget http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml";
  echo " $ openvas-portnames-update service-names-port-numbers.xml";
  echo " $ rm service-names-port-numbers.xml";
  exit 0
}

if [ ! -n "$1" ]; then
  do_help
fi

if [ ! -f "$1" ]; then
  echo "[e] Port names list $1 not found.";
  exit 1;
else
  XML="$1"
fi

# Configure DB_DIR where our DB is located.
if [ -z "$DB_DIR" ]; then
  OPENVASSD=`which openvassd`
  if [ -z "$OPENVASSD" ] ; then
    echo "[e] Error: openvassd is not in the path, could not determine the Manager directory."
    exit 1
  else
    OV_DIR=`openvassd -s | awk -F" = " '/^plugins_folder/ { print $2 }' | sed -s 's/\(^.*\)\/plugins/\1/'`
  fi
  DB_DIR="$OV_DIR/mgr"
fi

if [ $POSTGRES -eq 1 ]
then
  SQL="psql -v ON_ERROR_STOP=1 -q --pset pager=off --no-align -d tasks -t"
else
  TASKS_DB="$DB_DIR/tasks.db"
  if [ ! -f $TASKS_DB ]; then
	echo "$TASKS_DB not found. Rebuild DB before updating port names.";
	exit 1;
  fi
  SQL="sqlite3 $TASKS_DB"
fi

DATA_DIR=/usr/share/openvas
XSL="$DATA_DIR/openvasmd/portnames_update.xsl"
if [ ! -f $XSL ]; then
  echo "$XSL file not found.";
  exit 1;
fi

SED="sed s/^<.*>$//g"

COUNT=`xsltproc "$XSL" "$XML" | grep INSERT | wc -l`
xsltproc "$XSL" "$XML" | $SED | $SQL

echo "Updated $COUNT entries."
