#!/bin/bash

SLEEP_TIME="0.5"

#env > /tmp/123.txt
#Wayland: XAUTHORITY=/run/user/1000/.mutter-Xwaylandauth.N8Q651
#Xorg:    XAUTHORITY=/run/user/1000/gdm/Xauthority

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

echo -e "userName: $userName\npostfix: $postfix"

if [[ -d /home/$userName ]]
    then target="/home/$userName/hardware_report$postfix.tar.gz"
    else target="/tmp/hardware_report$postfix.tar.gz"
fi

echo "target = $target" >> /tmp/123.txt

title="Сбор диагностических данных"
text1="Запустить скрипт сбора данных об оборудовании и системных журналов?"
text_in_progress="Собираются необходимые сведения..."
text_cancelled="Отменено, работа не завершена!"
text_error="Произошла непредвиденная ошибка!"
text2="Будет создан архив $target"
text3="Отправьте полученный архив в поддержку Uncom OS\n \n$target"
#zenity --width=384 --height=128 --warning --title "$title"  --text "$text1\n$text2"

zenity  --width=384 --height=128 --question --title "$title"  --text "$text1\n\n$text2"; code=$?
if [ $code -eq 0 ]
    then echo "Proceeding..."
    else echo "Exiting..."
        exit 1
fi


tmpdir=`mktemp -d` ; code=$?
[[ $code -eq 0 ]] || {
    zenity --error --text="$text_error"
    exit 2
}

(
echo "10" ; sleep $SLEEP_TIME
lspci -vv > $tmpdir/lspci.txt

echo "20" ; sleep $SLEEP_TIME
lsusb -vv > $tmpdir/lsusb.txt

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

echo "40" ; sleep $SLEEP_TIME
cp /var/log/syslog $tmpdir

echo "60" ; sleep $SLEEP_TIME
cp /var/log/kern.log $tmpdir

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

echo "75" ; sleep $SLEEP_TIME
apt list --installed > $tmpdir/apt_list.txt

echo "80" ; sleep $SLEEP_TIME
pushd $tmpdir
GZIP=-9 tar -czvf $target *
popd

echo "90" ; sleep $SLEEP_TIME
rm -fr $tmpdir
) |
zenity --progress --width=384 --height=128 \
  --title="$title" \
  --text="$text_in_progress" \
  --auto-close \
  --auto-kill \
  --percentage=0

if [ "$?" -eq 2 ] ; then
    echo "Exiting"
    exit 2
fi

if [ "$?" = -1 ] ; then
        zenity --error \
          --text="$text_cancelled"
    [ -d $tmpdir ] && rm -fr $tmpdir
    exit 1
fi

chown $userName:$userName $target

zenity  --width=384 --height=128 --info --title "$title"  --text "$text3" && {
    echo "The End"
}
