#!/bin/sh
#
VERSION=1.2

ARG1="$1"

if [ -e ${ARG1} ];then
    ADDITIONALDATA="${ARG1}"
fi


TMPDATA=$(mktemp -d  -t benno-support-info_XXXXXXXXXXX)
TARDATA="${TMPDATA}/benno-config.tar"
CERTFILE="${TMPDATA}/cert.pem"
ENCFILE="${TMPDATA}/benno-config.data"
NOW=$(date +%y%m%d%H%M%S)
sleep 1
TAROUT="/tmp/benno-config_${NOW}.tar.gz"
ENCOUT="/tmp/benno-config_${NOW}.data"

(
echo "** Networking"
echo "* IP adresses"
/sbin/ip address show
echo ""
echo "* Hostname"
cat /etc/hostname
echo ""
echo "* Hosts file"
cat /etc/hosts
echo ""
echo "* TCP ports listening"
netstat -ltnp
echo ""
echo "** Filesystem"
echo "* /etc/benno"
ls -la /etc/benno
echo ""
echo "* /etc/benno-web"
ls -la /etc/benno-web
ls -la /etc/benno-web/auth.d
echo ""
echo "* /var/lib/benno-web"
ls -la /var/lib/benno-web
echo ""
echo "* /srv/benno"
ls -la /srv/benno
ls -la /srv/benno/archive
echo ""
echo "* DB VERSION"
[ -f /usr/bin/sqlite3 ] && sqlite3 /var/lib/benno-web/bennoweb.sqlite "SELECT id,value FROM appstate WHERE id = 'dbversion';"
) > ${TMPDATA}/systemconfig.txt
perl -p \
    -e 's/(authKey.*?\>)\w+?\</$1*************************/g;' \
    -e 's/(endpoint\>).+?\</$1*************************/g;' \
    -e 's/(region\>).+?\</$1*************************/g;' \
    -e 's/(privateKey.*?\>)\w+?\</$1*************************/g;' \
    -e 's/(keyPassword.*?\>)\w+?\</$1*************************/g;' \
    /etc/benno/benno.xml  > ${TMPDATA}/benno.xml
cd ${TMPDATA}
tar -chf \
    ${TARDATA} \
    /etc/benno/jetty.xml \
    /etc/benno/benno.lic \
    /etc/benno-web/benno.conf \
    /srv/benno/system \
    systemconfig.txt $ADDITIONALDATA 2>/dev/null
tar --newer="-7 days" -rf ${TARDATA} /var/log/benno/ /var/log/apache2/
gzip ${TARDATA}
TARGZ="${TARDATA}.gz"

echo "
-----BEGIN CERTIFICATE-----
[payload removed: 1440 characters in 23 lines]
-----END CERTIFICATE-----
" > ${TMPDATA}/cert.pem
 
cd - > /dev/null
 
openssl smime -encrypt -aes256 -in ${TARGZ} -binary -outform DER -out ${ENCFILE} ${CERTFILE}
echo "Die Daten wurden zusammengestellt und verschluesselt."
echo ""

/bin/mv -i ${TARGZ}   ${TAROUT}
/bin/mv -i ${ENCFILE} ${ENCOUT}

echo "Das temporaere Verzeichnis \"${TMPDATA}\" kann geloescht werden:"
echo "  rm -r  \"${TMPDATA}\""
echo ""
echo "Unverschluesselte Daten: ${TAROUT}"
echo "Verschluesselte Daten:   ${ENCOUT}"
echo ""

