#!/bin/bash

## Copyright (C) 2012 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -e

source /usr/libexec/msgcollector/msgcollector_shared
## sets: ${msgcollector_run_dir}
folder_init

check() {
   if ! [[ "$1" =~ ^[0-9a-zA-Z_-]+$ ]]; then
      echo "Invalid character!" >&2
      echo "\$1: $1" >&2
      exit 1
   fi
}

identifier="$1"
progressbaridx="$2"

check "$identifier"
check "$progressbaridx"

if [ ! -f "${msgcollector_run_dir}/${identifier}_${progressbaridx}_parentpid" ]; then
   exit 0
fi

parentpid="$(cat "${msgcollector_run_dir}/${identifier}_${progressbaridx}_parentpid")"

true "parentpid: '$parentpid'"

if [[ ! "$parentpid" == *[!0-9]* ]]; then
   true "parentpid is strictly numeric, ok."
else
   true "parentpid is not strictly numeric, exit."
   exit 0
fi

## Check if still running.
ps__p_exit_code="0"
ps -p "$parentpid" >/dev/null 2>/dev/null || { ps__p_exit_code="$?"; true; };

if [ "$ps__p_exit_code" = "0" ]; then
   true "Sending signal sigusr2 to $parentpid."
   kill -s sigusr2 "$parentpid"
else
   true "Not sending signal sigusr2 to parentpid $parentpid, because it is already terminated."
fi
