#!/bin/bash

# Kill any notifier(s) running
pkill -f 'python .*/usr/bin/apt-notifier.py'

ps -o args= $PPID | grep -q /usr/bin/apt-notifier-unhide-Icon
if [ "$?" -eq 0 ]
    then
      :
    else
      sleep .2
fi

# Do a redundant kill of any running notifier(s)
pkill -f 'python .*/usr/bin/apt-notifier.py'

sleep .1

# Remove any previously created /tmp/tmp****** files owned by current user,
# that have -rw------ permissions, and contain the pattern "sorted_list_of_upgrades()".
for i in $(cd /tmp; find . -user $USER -perm 600 -regextype posix-egrep -regex '\./tmp[[:print:]]{6}' 2>/dev/null | cut -c3-);
  do
    grep -q "sorted_list_of_upgrades()" /tmp/$i;[ $? -ne 0 ]||rm /tmp/$i
  done

# create the apt-notifierrc file if it doesn't already exist
if ! [ -f ~/.config/apt-notifierrc ];
then
  touch ~/.config/apt-notifierrc
  chmod 644 ~/.config/apt-notifierrc
fi

# Remove unneeded/unused[General] line from apt-notifierrc file if present.
sed -i '/^\[General\].*/Id' ~/.config/apt-notifierrc

# Remove unneeded/unused AutoStart line from apt-notifierrc file if present.
sed -i '/^AutoStart.*/Id' ~/.config/apt-notifierrc

grep -q -e ^UpgradeType=upgrade -e ^UpgradeType=dist-upgrade ~/.config/apt-notifierrc
if [ "$?" -eq 0 ]
  then
  :
  else
  #
  #if a UpgradeType line not present,
  #or not equal to 'upgrade' or 'dist-upgrade'
  #set it to 'UpgradeType=dist-upgrade'
  #
  sed -i '/^UpgradeType/d' ~/.config/apt-notifierrc
  echo -e 'UpgradeType=dist-upgrade\n'>> ~/.config/apt-notifierrc
fi

#test to see if ~/.config/apt-notifierrc contains any blank lines or lines with only whitespace
grep -q ^[[:space:]]*$ ~/.config/apt-notifierrc
if [ "$?" = "0" ]
  then
  #cleanup any blank lines or lines with only whitespace
    sed -i '/^[[:space:]]*$/d' ~/.config/apt-notifierrc
  else
  #no blank lines or lines with only whitespace so do nothing
    :
fi

# start the notifier (nicely)
#ionice -c3 nice -n19 python -m pdb /usr/bin/apt-notifier.py < <(sleep .5; echo c)& disown -h
ionice -c3 nice -n19 /usr/bin/python /usr/bin/apt-notifier.py & disown -h

# Fix Systray Icons - fehlix's method, not using
#sleep 3
#declare -A B=([true]=false [false]=true); xp() { xfconf-query -c xfce4-panel -p "${@}" ;}; SF=$(xp /plugins  --list | grep -m1 /show-frame 2>/dev/null) || exit 0; xp $SF -n -t bool -s ${B[$(xp $SF)]}; xp $SF -n -t bool -s ${B[$(xp $SF)]};

exit 0

