#!/bin/bash

# Kill any notifier(s) running
pkill -f 'python[23]? .*/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)
# started from /usr/bin - not used n the current version

if pgrep -f 'python[23]? .*/usr/bin/apt-notifier.py' >/dev/null; then
   pkill -f 'python[23]? .*/usr/bin/apt-notifier.py'
   sleep 0.1
fi

# started from /usr/lib/apt-notifer/modules/apt-notifier.py
if pgrep -f 'python3? .*/usr/lib/apt-notifier/modules/apt-notifier.py' >/dev/null; then
   pkill -f 'python3? .*/usr/lib/apt-notifier/modules/apt-notifier.py'
   sleep .1
fi

# rename user autostart script name
if [ -f ~/.config/autostart/mx-updater-autostart.desktop ]; then
   if [ -f ~/.config/autostart/apt-notifier-autostart.desktop ]; then
      rm ~/.config/autostart/mx-updater-autostart.desktop
   else
      mv ~/.config/autostart/mx-updater-autostart.desktop  ~/.config/autostart/apt-notifier-autostart.desktop
   fi
fi

# Remove any previously created /tmp/tmp****** files owned by current user,
# that have -rw------ permissions, and contain the pattern "sorted_list_of_upgrades()".
# not using those tmp-files  anymore - we keep it
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

CONF_FILE=~/.config/MX-Linux/apt-notifier.conf
CONF_OLD="[MX]
# apt-notifier defaults
#
# file: ~/.config/MX-Linux/apt-notifier.conf
# generated by apt-notifier at Mon 18 Jul 2022 12:09:22 AM CEST
#
# Updater Reload and Upgrade auto close timeouts in seconds
#
# Change default values below.
#
reload_auto_close_timeout    = 6
upgrade_auto_close_timeout   = 10"

CONF_NEW="$(cat <<'EOF' | sed 's/[[:space:]]*$//'
#
# Config items for apt-notifier "MX-Updater"
#
# file: ~/.config/MX-Linux/apt-notifier.conf
# generated by apt-notifier at $(date)
# This file will be recreated if it has been deleted.
#
# For all build-in config items see:
# /usr/share/apt-notifier/conf/apt-notifier.conf.d/01_apt-notifier.conf
#
# Comments starting with '#' sign  and empty lines are ignored
#
# Path items starting with  "$HOME/" or "~/", will be replaced
# with home directory of the user accordingly.

# Boolean items accept 'yes'/'no' or 'true'/'false'

# Un-comment and/or change default values below.

##Updater Reload and Upgrade auto close timeouts in seconds
#
reload_auto_close_timeout    = 6
upgrade_auto_close_timeout   = 10

##Tray icons
# Use 32x32 sized png icons with full path.
#
# classic_some                     = /usr/share/icons/mnotify-some-classic.png
# classic_none                     = /usr/share/icons/mnotify-none-classic.png
# pulse_some                       = /usr/share/icons/mnotify-some-pulse.png
# pulse_none                       = /usr/share/icons/mnotify-none-pulse.png
# wireframe_some                   = /usr/share/icons/mnotify-some-wireframe.png
# wireframe_none_dark              = /usr/share/icons/mnotify-none-wireframe-dark.png
# wireframe_none_light             = /usr/share/icons/mnotify-none-wireframe-light.png
# wireframe_none_dark_transparent  = /usr/share/icons/mnotify-none-wireframe-dark-transparent.png
# wireframe_none_light_transparent = /usr/share/icons/mnotify-none-wireframe-light-transparent.png

# Alternative apt/apt-get command line package manager
# use_nala = false

# Example section - will be ignored
#
[Example]
# comment out the section header line above to make it active
#
# Use of alternative classic_some- and clasic_none icons:
classic_none  = $HOME/.local/share/icons/apt-notifier-tickok_32.png
classic_some  = $HOME/.local/share/icons/apt-notifier-reload_32.png
#
# Use alternative apt/apt-get command line package manager
use_nala = true
EOF
)"

read MD5_CONF_OLD _ < <( echo "$CONF_OLD" | grep -v 'generated by apt-notifier' | md5sum)
read MD5_CONF_NEW _ < <( echo "$CONF_NEW" | grep -v 'generated by apt-notifier' | md5sum)

GENERATED_BY="# generated by apt-notifier at"
PULSE_NONE="# pulse_none"
PULSE_WHITE="# pulse_none                       = /usr/share/icons/mnotify-none-pulse-white.png"

CONF_NEW=$(sed "/^${GENERATED_BY}/c${GENERATED_BY} $(date)" <<<$CONF_NEW)
CONF_NEW_2=$(sed "/^${PULSE_NONE}/a${PULSE_WHITE}" <<<$CONF_NEW)
read MD5_CONF_NEW_2 _ < <( echo "$CONF_NEW_2" | grep -v 'generated by apt-notifier' | md5sum)

# create default timeouts conf entries
if [ -e /etc/mx-version ]; then
   #set -x
   # check "old" config extists and is not modified by the user
   if [ -e "$CONF_FILE" ]; then
      read MD5_CONF_FILE _ < <(grep -v 'generated by apt-notifier' "$CONF_FILE" |
                               sed 's/[[:space:]]*$//' |
                               md5sum )
      [ "$MD5_CONF_FILE" = "$MD5_CONF_OLD" ] &&  rm "$CONF_FILE"
      [ "$MD5_CONF_FILE" = "$MD5_CONF_NEW" ] &&  rm "$CONF_FILE"
   fi

   if ! [ -e "$CONF_FILE" ]; then
      [ -d ~/.config/MX-Linux ] || mkdir -p ~/.config/MX-Linux

      APT_NOTIFIER_UPDATER_CONFIG=/usr/lib/apt-notifier/bin/updater_config
      unset APT_NOTIFIER_DEFAULTS
      eval declare -A APT_NOTIFIER_DEFAULTS=(
           $($APT_NOTIFIER_UPDATER_CONFIG --shell 2>/dev/null |
              grep -E 'auto_close_timeout|_some|_none'
           )
        ) 2>/dev/null

      CONF_NEW_DEFAULTS=$(
      cat <<DEFAULTS | sed 's/^[[:space:]]*//'
        #
        # Config items for apt-notifier "MX-Updater"
        #
        # file: ~/.config/MX-Linux/apt-notifier.conf
        # generated by apt-notifier at $(date)
        # This file will be recreated if it has been deleted.
        #
        # For all build-in config items see:
        # /usr/share/apt-notifier/conf/apt-notifier.conf.d/01_apt-notifier.conf
        #
        # Comments starting with '#' sign  and empty lines are ignored
        #
        # Path items starting with  "\$HOME/" or "~/", will be replaced
        # with home directory of the user accordingly.

        # Boolean items accept 'yes'/'no' or 'true'/'false'

        # Un-comment and/or change default values below.

        ##Updater Reload and Upgrade auto close timeouts in seconds
        #
        reload_auto_close_timeout    = ${APT_NOTIFIER_DEFAULTS[reload_auto_close_timeout]:-6}
        upgrade_auto_close_timeout   = ${APT_NOTIFIER_DEFAULTS[upgrade_auto_close_timeout]:-10}

        ##Tray icons
        # Use 32x32 sized png icons with full path.
        #
        # classic_some                     = ${APT_NOTIFIER_DEFAULTS[classic_some]}
        # classic_none                     = ${APT_NOTIFIER_DEFAULTS[classic_none]}
        # pulse_some                       = ${APT_NOTIFIER_DEFAULTS[pulse_some]}
        # pulse_none                       = ${APT_NOTIFIER_DEFAULTS[pulse_none]}
        # wireframe_some                   = ${APT_NOTIFIER_DEFAULTS[wireframe_some]}
        # wireframe_none_dark              = ${APT_NOTIFIER_DEFAULTS[wireframe_none_dark]}
        # wireframe_none_light             = ${APT_NOTIFIER_DEFAULTS[wireframe_none_light]}
        # wireframe_none_dark_transparent  = ${APT_NOTIFIER_DEFAULTS[wireframe_none_dark_transparent]}
        # wireframe_none_light_transparent = ${APT_NOTIFIER_DEFAULTS[wireframe_none_light_transparent]}

        # Alternative apt/apt-get command line package manager
        # use_nala = true

        # Example section below will be ignored
        #
        [Example]
        # comment out the section header line above to make it active
        #
        # Use of alternative classic_some- and clasic_none icons:
        classic_none  = \$HOME/.local/share/icons/apt-notifier-tickok_32.png
        classic_some  = \$HOME/.local/share/icons/apt-notifier-reload_32.png
        #
        # Use alternative apt/apt-get command line package manager
        use_nala = true
DEFAULTS
)
    CONF_NEW="$CONF_NEW_DEFAULTS"
    if ! grep -q mnotify-none-pulse-white.png <<<$CONF_NEW; then
       CONF_NEW=$(sed "/^${PULSE_NONE}/a${PULSE_WHITE}" <<<$CONF_NEW)
    fi
    echo "$CONF_NEW" > ~/.config/MX-Linux/apt-notifier.conf
  fi
fi

# strip leading spaces 
if [ -e "$CONF_FILE" ]; then
   sed -i -r "s/^[[:space:]]+//" "$CONF_FILE"
fi

# start the notifier (nicely)
ionice -c3 nice -n19 /usr/bin/python3 /usr/lib/apt-notifier/modules/apt-notifier.py & disown -h 1>/dev/null 2>&1

# 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

