#!/bin/sh

PROCESS="/usr/lib/gosigndesktop/GoSignDesktop"

# if active, try clean stop
if pgrep --full --exact "$PROCESS" 1>/dev/null 2>/dev/null; then
  pgrep --full --exact "$PROCESS" 2>/dev/null | while IFS= read -r PROCESS_PID; do
    USER_UID=$(ps -p "$PROCESS_PID" -o euid= 2>/dev/null)
    if [ ! -z "$USER_UID" ]; then
      # scan displays
      find /tmp/.X11-unix/ -mindepth 1 -maxdepth 1 -type s 2>/dev/null | while IFS= read -r DISP; do
        DISPLAY_UID=$(stat --format=%u "$DISP")
        if [ "$USER_UID" -eq "$DISPLAY_UID" ]; then
          DISPLAY_IDENTIFIER=$(basename "$DISP" | tr 'X' ':')
          USER_NAME=$(id --user --name "$USER_UID")
          # set DISPLAY and send --die command as process user
          if [ ! -z "$DISPLAY_IDENTIFIER" ] && [ ! -z "$USER_NAME" ]; then
            DISPLAY="$DISPLAY_IDENTIFIER" sudo --user="$USER_NAME" "$PROCESS" --die 1>/dev/null 2>/dev/null
          fi
        fi
      done
    fi
  done
  # wait clean stop
  sleep 5
fi

# if survivors, kill
if pgrep --full --exact "$PROCESS" 1>/dev/null 2>/dev/null; then
  pkill -SIGUSR2 --full --exact "$PROCESS" 1>/dev/null 2>/dev/null
fi

exit 0
