#!/bin/bash
###############################################################
#                Unofficial 'Bash strict mode'                #
# http://redsymbol.net/articles/unofficial-bash-strict-mode/  #
###############################################################
set -euo pipefail
IFS=$'\n\t'
###############################################################

# Simplified from https://stackoverflow.com/a/49533938/2268426
DEBUG=${DEBUG:-false}

error_print() {
  local text="${1}"
  echo "${text}" >&2
}

get_display() {
  pgrep -a Xorg | awk '{print $3}'
}

get_user_using_display() {
  local display_to_find_user_for="${1}"
  who | grep "(${display_to_find_user_for})" | awk '{print $1}' | head -n 1
}

send_notification() {
  local user="${1}"
  local display="${2}"
  shift
  shift

  sudo -u "${user}" \
    "DISPLAY=${display}" \
    "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u "${user}")/bus" \
    /usr/bin/notify-send "$@"
}

run_main() {
  display="$(get_display)"

  if [[ -z "${display}" ]]; then
    error_print "Unable to get a display"
    exit 1
  fi

  for attempt in {1..10}; do
    user="$(get_user_using_display "${display}")"
    if [[ -n "${user}" ]]; then
      break
    else
      sleep 1
    fi
  done

  if [[ -z "${user}" ]]; then
    error_print "No user found to be using display in time - skipping notification"
    exit 1
  fi

  send_notification "${user}" "${display}" "$@"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  run_main "$@"
fi
