#!/bin/sh
#
# OpenVAS Manager
# $Id$
# Description: Report generator script: ISM Verinice interface.
#
# Authors:
# Andre Heinecke <aheinecke@intevation.de>
#
# Copyright:
# Copyright (C) 2011 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.

TMP=`mktemp -d` || exit 1
STARTDIR=`pwd`
XMLFILE=`readlink -f $1`
DATE=`xmlstarlet sel -t -v /report/scan_start "$XMLFILE" | cut -c 1-10`

SCAN_NAME=`xmlstarlet sel -t -v /report/task/name "$XMLFILE"`

SCAN_NAME=$(echo $SCAN_NAME | sed 's/ /_/g')

# File size above which the attachments should be compressed
COMPRESS_SIZE=10485760

mkdir -p  $TMP/files
FILENAME=${SCAN_NAME}_${DATE}.xml
FILELOC=$TMP/files/${FILENAME}
HTML_FILELOC=$(echo $FILELOC | sed 's/\.xml/\_HTML.html/')
HTML_FILE=$(echo $FILENAME | sed 's/\.xml/\_HTML.html/')
HTML_MIMETYPE="html"

HTML_REQUESTED=`cat $1 | xmlstarlet sel -t -v "/report/report_format/param[name='Attach HTML report']/value"`

if [ -n "$HTML_REQUESTED" ] && [ "$HTML_REQUESTED" -eq 1 ]
then
  xsltproc ./html.xsl $1 > "$HTML_FILELOC"
  if [ `wc -c < "$HTML_FILELOC"` -ge $COMPRESS_SIZE ]
  then
    zip -j -q `echo $HTML_FILELOC | sed 's/\.html/\.zip/'` "$HTML_FILELOC"
    rm -f "$HTML_FILELOC"
    HTML_FILELOC=$(echo $FILELOC | sed 's/\.xml/\_HTML.zip/')
    HTML_FILE=$(echo $FILENAME | sed 's/\.xml/\_HTML.zip/')
    HTML_MIMETYPE="zip"
  fi
fi

xsltproc --stringparam htmlfilename "$HTML_FILE" \
         --stringparam htmlmimetype "$HTML_MIMETYPE" \
         --stringparam filedate `stat -c %Z $XMLFILE` ./Verinice_ISM.xsl $1 | \
        sed -e "s/\ xmlns=\"\"//g" | \
        xmlstarlet fo >  $TMP/verinice.xml && \
cd $TMP && zip -r - *
cd $STARTDIR
rm -r $TMP
