#!/bin/sh

# needrestart-notify-ez v0.1
# Modernized and user-friendly version of 400-notify-send
# Copyright (c) 2026 Raphaël Halimi <raphael.halimi@gmail.com>

# Source needrestart notify functions
. /usr/lib/needrestart/notify.d.sh

# Use our own gettext domain
export TEXTDOMAIN="needrestart-notify-ez"


#
# Variables
#

STATE="/run/needrestart-notify-ez"
REBOOT="/run/reboot-required"
PROGS="Firefox Thunderbird"
CONFIG="/etc/needrestart/notify-ez.conf"


#
# Functions
#

# Print message
print_message () { printf "[%s] %s\n" "$0" "$1" >&2 ; }

# Die
die () { print_message "ERROR: ${1:-Fatal error}" ; exit 1 ; }

# Create statefile
create_statefile () { printf "%i\n" "$NR_PID" > "$STATE" ; }

# Notify function
notify () {
  local TYPE MSGTITLE MSGBODY
  TYPE="$1"

  # Notify user only once per needrestart run for each notification type
  grep -q -E -x "$NR_USERNAME,$TYPE,$PROG" "$STATE" && return 0

  # Set notification text
  case "$TYPE" in
    system) MSGTITLE="$(gettext "System restart required")" MSGBODY="$(gettext "An essential system component has been updated. Please restart your computer as soon as possible.")" ;;
    session) MSGTITLE="$(gettext "Session restart required")" MSGBODY="$(gettext "The system has been updated. Please restart your session as soon as possible.")" ;;
    prog) MSGTITLE="$(gettext "Restart of") $PROG $(gettext "required")" MSGBODY="$PROG $(gettext "(or one of its libraries) has been updated. Please restart it as soon as possible.")" ;;
  esac

  # Notify user
  runuser -p -u "$NR_USERNAME" -- notify-send -a needrestart -u critical -i dialog-warning "$MSGTITLE" "$MSGBODY"

  # Update state file
  printf "%s,%s,%s\n" "$NR_USERNAME" "$TYPE" "$PROG" >> "$STATE"
}


#
# Checks
#

# Check dependencies
command -v "notify-send" >/dev/null || die "Command 'notify-send' not found"

# Check needrestart configuration
[ "$NR_NOTIFYD_DISABLE_NOTIFY_SEND" = '1' ] && die "disabled in global config"

# Find session bus address
DBUS_SESSION_BUS_ADDRESS=$(sed -z -n s/^DBUS_SESSION_BUS_ADDRESS=//p "/proc/$NR_SESSPPID/environ")
if [ "$DBUS_SESSION_BUS_ADDRESS" ] ; then
  export DBUS_SESSION_BUS_ADDRESS
  print_message "notify user $NR_USERNAME"
else
  die "DBus session bus address not found for process $NR_SESSPPID"
fi

# Create state file once per needrestart run
NR_PID="$(pgrep needrestart)"
if [ -e "$STATE" ] ; then
  # If state file was created by a previous needrestart run, overwrite it
  [ "$(sed -n '1 { p ; q }' "$STATE")" = "$NR_PID" ] || create_statefile
else
  create_statefile
fi


#
# Main
#

# Save the list of obsolete processes
OBSOLETE="$(cat)"

# Notify user if a reboot is required
[ -e "$REBOOT" ] && notify "system"

# Notify user if a session restart is required
notify "session"

# Per-prgram notifications
for PROG in $PROGS ; do
  if printf "%s" "$OBSOLETE" | grep -q -i "$PROG" ; then
    notify "prog" "$PROG"
  fi
done
