#!/bin/bash

#test to see if started by apt-notifier.py,
#if it was resize terminal window to 67% of screenwidth & screenheight,
#and reposition to the center of screen
sleep 1
ps axjf | grep ^[[:space:]]*$$ -B7 -E | grep apt-notifier.py$ -qo
if [ "$?" = "0" ]
  then
    IFS='x' read screenWidth screenHeight < <(xdpyinfo | grep dimensions | grep -o '[0-9x]*' | head -n1)
    xdotool getactivewindow windowsize --usehints 67% 67%
    read width height < <(xdotool getactivewindow getwindowgeometry --shell | head -5 | tail -2 | cut -f2 -d= | sed ':a;N;$!ba;s/\n/ /g')
    newPosX=$(((screenWidth-width)/2))
    newPosY=$(((screenHeight-height)/2))
    xdotool getactivewindow windowmove "$newPosX" "$newPosY"
fi

ShowUnattendedUpgradesLogs()
{
 ls -1tr /var/log/unattended-upgrades/unattended-upgrades.log* |\
                                                                \
 xargs zcat -fq                                                |\
                                                                \
 sed 's/origin=/\norigin=/g'                                   |\
 sed 's/, \x27a=/,\n\x27a=/g'                                  |\
 sed 's/, \x27c=/,\n\x27c=/g'                                  |\
 sed 's/, \x27l=/,\n\x27l=/g'                                  |\
 sed 's/, \x27n=/,\n\x27n=/g'                                  |\
 sed 's/, o=/,\no=/g'                                          |\
 sed 's/, \x27archive=/,\n\x27archive=/g'                      |\
 sed 's/, \x27codename=/,\n\x27codename=/g'                    |\
 sed 's/, \x27component=/,\n\x27component=/g'                  |\
 sed 's/, \x27label=/,\n\x27label=/g'                          |\
 sed 's/, \x27origin=/,\n\x27origin=/g'                        |\
 sed 's/, \x27suite=/,\n\x27suite=/g'
}
#set strings using translations from the apt-notfier.py python script
LessPrompt="` gettext -d apt-notifier \"Press 'h' for help, 'q' to quit\"`"
NoLogsFound="`gettext -d apt-notifier \"No logs found.\"`"
SeeHistory="` gettext -d apt-notifier \"For a less detailed view see 'Auto-update dpkg log(s)' or 'History'.\"`"

if [ -f /var/log/unattended-upgrades/unattended-upgrades.log ]
  then 
    StartOfLatestEntry="$(ShowUnattendedUpgradesLogs | grep 'Initial blacklist : ' | awk '{print $1,$2}' | tail -n 1)"
    ShowUnattendedUpgradesLogs | sed -e "\$a\\\n${SeeHistory}\\\\\n" | sed 's/\\$//' | less -~ -R --prompt="--less--[$LessPrompt]" -p "${StartOfLatestEntry}"
  else
    echo -e \\n"${NoLogsFound}"\\n | less -~ -R --prompt="--less--[$LessPrompt]"
fi

exit
