#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;93m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color

SLEEP_TIME="0.5"

echo -e "${GREEN}You are running ina-diagnostics (console)${NC}"

whoami | grep root
if [[ "$?" -eq 0 ]]
    then postfix="_su"
        userID=`env | grep SUDO_USER | awk -F\= '{print $NF}'`
        userName=`cat /etc/passwd | grep $userID | awk -F: '{print $1}'`
    else postfix="_user"
        userName=`whoami`
fi

#echo -e "userName: $userName\npostfix: $postfix"
# date like 8 March 2024 17-48: 08.03.2024_17.48
date_part=`date '+%d.%m.%Y_%H.%M'`
# hostname cut to first 5 symbols
host_name=`hostname | cut -c1-5`

if [[ -d /home/$userName ]]
    then target="/home/$userName/hw_report$postfix.$date_part.$host_name.tar.gz"
    else target="/tmp/hw_report$postfix.$date_part.$host_name.tar.gz"
fi
echo -e "${GREEN}The following file will be created: $target ${NC}"
echo
echo -e "${MAGENTA}Press any key to continue...${NC}"
read


tmpdir=`mktemp -d` ; code=$?
[[ $code -eq 0 ]] || {
    echo -e "${RED}Error code 2, exiting${NC}"
    exit 2
}

sleep $SLEEP_TIME
lspci -vv > $tmpdir/lspci.txt

sleep $SLEEP_TIME
lsusb -vv > $tmpdir/lsusb.txt

sleep $SLEEP_TIME
uname -a  > $tmpdir/dmidecode.txt
echo "dmidecode output:" >> $tmpdir/dmidecode.txt
dmidecode >> $tmpdir/dmidecode.txt

sleep $SLEEP_TIME
[ -d /usr/share/upmd/ ] && {
    cp /usr/share/upmd/* $tmpdir
}
[[ -f /var/ina/ina-license/machine-hash ]] && cp /var/ina/ina-license/machine-hash $tmpdir

sleep $SLEEP_TIME
cp /var/log/syslog $tmpdir

sleep $SLEEP_TIME
[ -f /var/log/ina-update.log ] && {
    cp /var/log/ina-update.log $tmpdir
}
[ -f /var/log/ina-kernel68-update.log ] && {
    cp /var/log/ina-kernel68-update.log $tmpdir
}

sleep $SLEEP_TIME
cp /usr/bin/ina-activate $tmpdir
cp /usr/lib/ina/ina-license/ina-activate.py $tmpdir

sleep $SLEEP_TIME
i="1"
for log in `find /var/lib/dkms/ -name "make.log"`
do
    cp $log $tmpdir/make.log.$i
    i=`expr $i \+ 1`
done

sleep $SLEEP_TIME
cp /var/log/kern.log $tmpdir

sleep $SLEEP_TIME
cp /etc/apt/sources.list $tmpdir
ls -l /etc/apt/sources.list.d/ >> $tmpdir/apt.other.ls

if [ "$postfix" == "_user" ]
then sleep $SLEEP_TIME
    pactl list cards > $tmpdir/pactl.txt
fi

apt list --installed > $tmpdir/apt_list.txt
flatpak -d list > $tmpdir/flatpak_list.txt

sleep $SLEEP_TIME
pushd $tmpdir
GZIP=-9 tar -czvf $target *
popd

sleep $SLEEP_TIME
rm -fr $tmpdir

ls $target
if [ "$?" = -1 ] ; then
    echo -e "${RED}Error code 1, exiting${NC}"
    [ -d $tmpdir ] && rm -fr $tmpdir
    exit 1
fi

chown $userName:$userName $target

echo -e "${GREEN}The work is done.${NC}"
