#!/bin/bash
#
#
#   OPEN-XCHANGE legal information
#
#   All intellectual property rights in the Software are protected by
#   international copyright laws.
#
#
#   In some countries OX, OX Open-Xchange, open xchange and OXtender
#   as well as the corresponding Logos OX Open-Xchange and OX are registered
#   trademarks of the Open-Xchange, Inc. group of companies.
#   The use of the Logos is not covered by the GNU General Public License.
#   Instead, you are allowed to use these Logos according to the terms and
#   conditions of the Creative Commons License, Version 2.5, Attribution,
#   Non-commercial, ShareAlike, and the interpretation of the term
#   Non-commercial applicable to the aforementioned license is published
#   on the web site http://www.open-xchange.com/EN/legal/index.html.
#
#   Please make sure that third-party modules and libraries are used
#   according to their respective licenses.
#
#   Any modifications to this package must retain all copyright notices
#   of the original copyright holder(s) for the original code used.
#
#   After any such modifications, the original and derivative code shall remain
#   under the copyright of the copyright holder(s) and/or original author(s)per
#   the Attribution and Assignment Agreement that can be located at
#   http://www.open-xchange.com/EN/developer/. The contributing author shall be
#   given Attribution for the derivative code and a license granting use.
#
#    Copyright (C) 2004-2013 Open-Xchange, Inc.
#    Mail: info@open-xchange.com
#
#
#    This program is free software; you can redistribute it and/or modify it
#    under the terms of the GNU General Public License, Version 2 as published
#    by the Free Software Foundation.
#
#    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., 59
#    Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#

OXFUNCTIONS=/opt/open-xchange/lib/oxfunctions.sh
TAR=$(type -P tar)
BZIP2=$(type -P bzip2)

test -f $OXFUNCTIONS || {
        echo "missing common shell functions file"
        exit 1
}

# check for "tar" executable
[ -x "$TAR" ] || {
	echo "missing needed command tar"
	exit 1
}

# check for "bzip2" executable
[ -x "$BZIP2" ] || {
   echo "missing needed command bzip2"
   exit 1
   }
. $OXFUNCTIONS

export PATH="$PATH:/opt/open-xchange/sbin"

# some defaults
PATH="${PATH}:/opt/open-xchange/sbin"
TMP=/tmp
TMP_LONG=tempdir
LOGDIR=ox_support_infos-$(date +%Y%m%d-%H%M%S)
LOGDIR_LONG=logdir
LOGARC=$TMP/$LOGDIR.tar.gz
LOGARC_LONG=log-archive
KEEP_TMP=false
KEEP_TMP_LONG=keep-tmp-files
KEEP_TMP_VALUES="true false"

# NOTE: Do not add arbitrary directories here!
ARCHIVE_DIRS="/opt/open-xchange/etc /var/log/open-xchange"

PROCS='showruntimestats -a;showruntimestats -c;showruntimestats -g;route -n;ps faux;top -bHn 1;dmesg;df;mount;netstat -putane;free;report -d;listbundles;listservices;uname -a'

MUSTOPTS="TMP LOGDIR KEEP_TMP LOGARC"
LONGOPTS='$TMP_LONG:,$LOGDIR_LONG:,$LOGARC_LONG:,$KEEP_TMP_LONG:'

usage() {
    echo
    echo "$0 currently knows the following parameters:"
    echo
    local lopts=$(echo $LONGOPTS | sed -e 's/[:,]/ /g')
    printf '%-22s | %-45s | %-s\n' "Parameter" "Default value" "Possible values"
    echo "--------------------------------------------------------------------------------------------"
    for opt in $lopts; do
	local rvar=${opt%_LONG}
	GLOBIGNORE='*'
	local default="$(eval echo "$rvar")"
	local possible=$(eval echo ${opt%_LONG}_VALUES)
	local lopt=$(eval echo $opt)
        # echo $opt $rvar $default $lopt
	printf '%-22s | %-45s | %-s\n' "--$lopt" $default "$possible"
	GLOBIGNORE=
    done
cat<<EOF

Example:

  $0 

use -D for Debug mode

EOF
    echo
#    exit 1
}


TEMP=$(POSIXLY_CORRECT=true getopt -o s:i:l:hD --long "$(eval echo $LONGOPTS),help" -- "$@") \
	|| die "exiting"

eval set -- "$TEMP"

while true; do
    case "$1" in
        --$TMP_LONG)
	    TMP=$2
	    shift 2
	    ;;
	--$LOGDIR_LONG)
	    LOGDIR=$2
	    shift 2
	    ;;
	--$KEEP_TMP_LONG)
	    KEEP_TMP=$2
	    shift 2
	    ;;
	--$LOGARC_LONG)
	    LOGARC=$2
	    shift 2
	    ;;
	-h|--help)
	    usage
	    exit
	    shift
	    ;;
	-D)
	    set -x
	    shift
	    ;;
	--)
	    shift
	    break
	    ;;
	*)
	    die "Internal error!"
	    exit 1
	    ;;
    esac
done

if [ $(id -u) -ne 0 ]; then
    die "need to be root in order to collect all needed data"
fi


# generic parameter checking
for opt in $MUSTOPTS; do
    opt_var=$(eval echo \$$opt)
    opt_var_long=$(eval echo \$${opt}_LONG)
    if [ -z "$opt_var" ]; then
        usage;
	    die "missing required option --$opt_var_long"
    fi
done

# generic option checking
ALLOPTS=$(echo $LONGOPTS | sed -e 's/[$:,]/ /g' -e 's/_LONG//g')
for opt in $ALLOPTS; do
    opt_var=$(eval echo \$$opt)
    opt_var_long=$(eval echo \$${opt}_LONG)
    opt_var_values=$(eval echo \$${opt}_VALUES)
    if [ -n "$opt_var_values" ]; then
	found=
	for val in $opt_var_values; do
	    if [ "$val" == "$opt_var" ]; then
		found=$val
	    fi
	done
	if [ -z "$found" ]; then
	    die "\"$opt_var\" is not a valid option to --$opt_var_long"
	fi
    fi
done

# distribution depending staff should go here

ox_system_type
DIST=$?

if [ $(( $DIST & $DEBIAN )) -eq $DEBIAN ]; then
     echo Debian system detected
     ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/debian_version"
     PROCS=${PROCS}';dpkg -l'
     test -f /etc/mysql/my.cnf && ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/mysql/my.cnf"
elif [ $(( $DIST & $UCS )) -eq $UCS ]; then
     echo "Univention system detected"
     ARCHIVE_DIRS="$ARCHIVE_DIRS /var/log/univention*"
     PROCS=${PROCS}';dpkg -l;ucr dump'
     test -f /etc/mysql/my.cnf && ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/mysql/my.cnf"
elif [ $(( $DIST & $SUSE )) -eq $SUSE ]; then
     echo SuSE system detected
     ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/SuSE-release"
     PROCS=${PROCS}';rpm -qa --last'
     test -f /etc/my.cnf && ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/my.cnf"
elif [ $(( $DIST & $REDHAT )) -eq $REDHAT ]; then
     echo Redhat system detected
     ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/redhat-release"
     PROCS=${PROCS}';rpm -qa --last'
     test -f /etc/my.cnf && ARCHIVE_DIRS="$ARCHIVE_DIRS /etc/my.cnf"
else
     echo Distribution not detected
fi

collect_files() {
   $TAR cvf /$TMP/$LOGDIR/ox_files_and_logs.tar --ignore-failed-read ${ARCHIVE_DIRS} > /dev/null 2>&1
   OIFS=$IFS
   IFS=$'\n'
   # be very selective on what to add to the archive (Bug#28830)
   for dir in /etc/httpd /etc/apache*; do
       test -d $dir || continue
       for file in $(find $dir -type f \
                               -regex '^.*\.conf$' -o \
			       -regex '^.*-\(enabled\|availabled\)\/.*$'); do
           ALLFILES="$ALLFILES $file"
       done
   done
   IFS=$OIFS
   $TAR rvf /$TMP/$LOGDIR/ox_files_and_logs.tar --ignore-failed-read $ALLFILES > /dev/null 2>&1
   bzip2 -9 /$TMP/$LOGDIR/ox_files_and_logs.tar
}


collect_output(){
   cd /$TMP
   IFS=";"
   for i in $PROCS; do
       unset IFS
       $i > "/$TMP/$LOGDIR/commands/$i" 2>&1
       IFS=";"
   done
   unset IFS
   cd - > /dev/null 2>&1
}

clean_up(){
   test "$KEEP_TMP" = "true" || rm -rf $TMP/$LOGDIR
}

trap "rm -f $LOGARC; clean_up; exit 1" SIGINT SIGSEGV SIGQUIT SIGTERM

echo creating logdir $TMP/$LOGDIR
mkdir -p $TMP/$LOGDIR/commands/
echo collecting files into $TMP/$LOGDIR/ox_files_and_logs.tar.bz2 
collect_files
echo collecting system data into $TMP/$LOGDIR
collect_output
echo creating archive $LOGARC
$TAR cvfz $LOGARC -C $TMP $LOGDIR > /dev/null 2>&1
clean_up
