#!/bin/bash

#/**
#@file    supportsave
#@brief   This script creates a tarball containing all logs and necesary files in order to debug a remote system.
#@brief   Initially the tarball would be manually sent by the final user to the support team.
#@brief   On a second stage this support save would be inclued in the GUI.
#@usage   supportsave
#@version 1.1.0
#@author  Fredy <aluque@soleta.eu>
#@date    2018-03-01
#*/ ##


# Basic structure
# Date, Hostname and Paths
# List of desired files to be saved
# Usefull system commands output to be saved (ie. uname -a > file.txt)
# Final compression

PATH=/bin:/sbin:/usr/bin:/usr/sbin

tmp_name=`date +%Y%m%d_%H%M`
hostname=`hostname`
home_dir="/opt/opengnsys"
ss_dir="supportsave_${hostname}_${tmp_name}"
prefix="/tmp"

if [ ! -d ${home_dir} ]; then
    echo "ERROR: The OpenGnsys directory does not exist." >&2
    exit 1
fi

source ${home_dir}/lib/ogfunctions.sh || exit 1

[ "$*" == "help" ] && help
[ "$*" == "version" ] && version
[ "$*" ] && raiseError usage
[ "$(whoami)" != "root" ] && raiseError access "Need to be root."

if [ -d "$1" ]; then
    prefix=${1}
fi

backup_dir="${prefix}/${ss_dir}"

config_paths="${home_dir}/etc ${home_dir}/tftpboot/menu.lst ${home_dir}/client/etc ${home_dir}/log /etc/default/opengnsys"
other_paths="/var/log/syslog* /var/log/messages*"

echo "Saving information for support in the path ${backup_dir}.tar.gz"
mkdir -p $backup_dir


echo "Saving system information:"
#################################

echo "- System version"
if [ -r /etc/os-release ]; then
    cat /etc/os-release                 >> $backup_dir/operating_system.txt 2>&1
elif which lsb_release &>/dev/null; then
    lsb_release -a                      >> $backup_dir/operating_system.txt 2>&1
elif [ -r /etc/system-release ]; then
    cat /etc/system-release             >> $backup_dir/operating_system.txt 2>&1
fi

echo "- Hardware"
echo "--- hostname ---"                 >> $backup_dir/hardware.txt
hostname                                >> $backup_dir/hardware.txt 2>&1
echo -e "\n--- dmidecode ---"           >> $backup_dir/hardware.txt
dmidecode                               >> $backup_dir/hardware.txt 2>&1
echo -e "\n--- lshw -short ---"         >> $backup_dir/hardware.txt
lshw -short                             >> $backup_dir/hardware.txt 2>&1
echo -e "\n--- lspci ---"               >> $backup_dir/hardware.txt
lspci                                   >> $backup_dir/hardware.txt 2>&1
echo -e "\n--- lsusb ---"               >> $backup_dir/hardware.txt
lsusb                                   >> $backup_dir/hardware.txt 2>&1

echo "- Kernel"
echo "--- uname -a ---"                 >> $backup_dir/kernel.txt
uname -a                                >> $backup_dir/kernel.txt 2>&1
echo -e "\n--- lsmod ---"               >> $backup_dir/kernel.txt
lsmod                                   >> $backup_dir/kernel.txt 2>&1
echo -e "\n--- Boot parameters ---"     >> $backup_dir/kernel.txt
cat /proc/cmdline                       >> $backup_dir/kernel.txt 2>&1
echo "- Kernel boot messages"
echo -e "\n--- dmesg ---"                    >> $backup_dir/kernel.txt
dmesg                                   >> $backup_dir/kernel.txt 2>&1

echo "- Packages"
if [ -f /etc/debian_version ]; then
    echo "--- dpkg -l ---"              >> $backup_dir/package_list.txt
    dpkg -l                             >> $backup_dir/package_list.txt 2>&1
elif [ -f /etc/redhat-release ]; then
    echo "--- rpm -qa ---"              >> $backup_dir/package_list.txt
    rpm -qa | sort                      >> $backup_dir/package_list.txt 2>&1
else
    echo "- WARNING: The package list can not be retrieved" | tee $backup_dir/package_list.txt
fi

echo "- Processes"
echo "ps aux"                           >> $backup_dir/ps.txt
ps aux                                  >> $backup_dir/ps.txt 2>&1

echo "- Resources"
echo "--- Uptime information ---"       >> $backup_dir/system_resources.txt
uptime                                  >> $backup_dir/system_resources.txt 2>&1
echo -e "\n--- Memory information ---"  >> $backup_dir/system_resources.txt
free -m                                 >> $backup_dir/system_resources.txt 2>&1
echo -e "\n--- CPU information ---"     >> $backup_dir/system_resources.txt
cat /proc/cpuinfo                       >> $backup_dir/system_resources.txt 2>&1
echo -e "\n--- TOP information ---"     >> $backup_dir/system_resources.txt
top -b -n1                              >> $backup_dir/system_resources.txt 2>&1

echo "- Filesystems"
echo "--- cat /etc/fstab ---"           >> $backup_dir/filesystems.txt
cat /etc/fstab                          >> $backup_dir/filesystems.txt 2>&1
echo -e "\n--- df -h ---"               >> $backup_dir/filesystems.txt
df -h                                   >> $backup_dir/filesystems.txt 2>&1
echo -e "\n--- blkid ---"               >> $backup_dir/filesystems.txt
blkid                                   >> $backup_dir/filesystems.txt 2>&1
echo -e "\n--- lsblk -Jbp ---"          >> $backup_dir/filesystems.txt
lsblk -Jbp                              >> $backup_dir/filesystems.txt 2>&1


echo "Saving network information:"
##################################

echo "- Interfaces"
ifconfig -a                             >> $backup_dir/ifconfig.txt 2>&1
ip link show                            >> $backup_dir/ip_link.txt 2>&1
ip addr show                            >> $backup_dir/ip_addr.txt 2>&1

echo "- Routes"
for i in `cat /etc/iproute2/rt_tables  | grep "table_" | awk {'print $2'}`
do
    echo "ip route list table $i"       >> $backup_dir/route.txt
    ip route list table $i              >> $backup_dir/route.txt 2>&1
done
echo "ip route list table main"         >> $backup_dir/route.txt
ip route list table main                >> $backup_dir/route.txt 2>&1
echo "ip rule list"                     >> $backup_dir/route.txt
ip rule list                            >> $backup_dir/route.txt 2>&1

echo "- Sockets"
echo "netstat -putan"                   >> $backup_dir/netstat.txt
netstat -putan                          >> $backup_dir/netstat.txt 2>&1
echo "netstat -nr"                      >> $backup_dir/netstat.txt
netstat -nr                             >> $backup_dir/netstat.txt 2>&1

echo "- Netfilter"
echo "Filter table "                    >> $backup_dir/netfilter.txt
iptables -nL -t filter                  >> $backup_dir/netfilter.txt 2>&1
echo -e "\nNAT table "                  >> $backup_dir/netfilter.txt
iptables -nL -t nat                     >> $backup_dir/netfilter.txt 2>&1
echo -e "\nMangle table "               >> $backup_dir/netfilter.txt
iptables -nL -t mangle                  >> $backup_dir/netfilter.txt 2>&1
echo -e "\nRaw table "                  >> $backup_dir/netfilter.txt
iptables -nL -t raw                     >> $backup_dir/netfilter.txt 2>&1

echo "- nf_conntrack"
if which conntrack &>/dev/null; then
    conntrack -L                        >> $backup_dir/conntrack.txt 2>&1
fi

echo "- ipset"
if which ipset &>/dev/null; then
    ipset save                          >> $backup_dir/ipset_tables.txt 2>&1
fi

echo "Saving OpenGnsys information:"
##################################

echo "- OpenGnsys version"
#echo `dpkg -l | grep opengnsys\  | awk '{print $3}'` > $backup_dir/opengnsys_version
curl -ks --connect-timeout 10 https://localhost/opengnsys/rest/info | jq . > ${backup_dir}/opengnsys_version.txt 2>/dev/null
if [ ! -s ${backup_dir}/opengnsys_version.txt ]; then
    cp -a ${home_dir}/doc/VERSION.txt ${backup_dir}/opengnsys_version.txt 2>&1
fi

echo "- Directory list"
ls -Ral ${home_dir}                     >> $backup_dir/opengnsys_files.txt 2>&1

if [ -r ${home_dir}/etc/ogAdmServer.cfg ]; then
    echo "- Database schema"
    source ${home_dir}/etc/ogAdmServer.cfg
    mysqldump -u "$USUARIO" -p"$PASSWORD" -d "$CATALOG" >> ${backup_dir}/opengnsys_schema.sql 2>&1
else
    echo "- WARNING: The OpenGnsys database can not be accessed" | tee ${backup_dir}/db_schema.txt
fi

echo "- Configuration and log files"
# Looking for huge log files (> 1 MB).
for log in $(find ${home_dir}/log -name "*.log" -size +1024 -print); do
    # Copying last 5000 lines and excluding file.
    tail -5000 ${log} > ${log}-tail5k 2>&1
    config_paths="$config_paths --exclude=${log}"
done
tar zcf ${backup_dir}/opengnsys_config.tar.gz ${config_paths} 2>/dev/null

echo "Saving other files"
##############################
tar zcf ${backup_dir}/logs.tar.gz ${other_paths} 2>/dev/null

echo "Packing supportsave"
##########################
cd ${prefix}
tar zcf ${ss_dir}.tar.gz ${ss_dir} 2>/dev/null
cd - >/dev/null

echo "Cleaning temporal files"
##########################
rm -rf ${backup_dir} ${home_dir}/log/*-tail5k

ls -lh ${backup_dir}.tar.gz
