#!/bin/bash

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

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

## provides: check_is_not_empty_and_only_one_line
## provides: is_whole_number
## provides: read_integer_file
source /usr/libexec/helper-scripts/strings.bsh

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

check() {
  local variable_to_check
  variable_to_check="$1"

  check_is_not_empty_and_only_one_line variable_to_check

  if ! printf '%s\n' "$variable_to_check" | unicode-show >/dev/null; then
    stecho "$0: Invalid character! variable_to_check:" >&2
    printf '%s\n' "'$variable_to_check'" | unicode-show >&2
    exit 1
  fi

  check_is_alpha_numeric variable_to_check
}

if ! [[ -v 1 ]]; then
  stecho "$0: ERROR: missing parameter 1!" >&2
  exit 1
fi
if ! [[ -v 2 ]]; then
  stecho "$0: ERROR: missing parameter 2!" >&2
  exit 1
fi

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

check "$identifier"
check "$progressbaridx"

full_path="${msgcollector_run_dir}/${identifier}_${progressbaridx}_parentpid"
check_is_not_empty_and_only_one_line full_path

if [ ! -f "$full_path" ]; then
  true "$0: INFO: parentpid file does not exist."
  exit 0
fi

parentpid="$(read_integer_file "$full_path")"

true "$0: INFO: parentpid: '$parentpid'"

if ps -p "$parentpid" &>/dev/null; then
  true "$0: INFO: Sending signal sigusr2 to $parentpid."
  kill -s sigusr2 "$parentpid"
else
  true "$0: INFO: Not sending signal sigusr2 to parentpid $parentpid, because it is already terminated."
fi
