#!/usr/bin/bash

readonly default_service='psd.service'

_compare_config_notice() {
  printf 'Compare /usr/share/psd/psd.conf with ~/.config/psd/psd.conf before starting "%s" again!\n' "$default_service"
}

_stop_user_unit_for_logged_in_users() {
  # If a logged-in user currently runs a specific user unit, it is stopped.
  #
  # The name of the user unit is provided by the first argument to this function.
  readonly service="$1"

  readarray -t users < <(loginctl --no-legend list-users | cut -f 2 -d ' ')

  for user in "${users[@]}"; do
    if systemctl --user --machine="$user"@.host --quiet is-active "$service"; then
      printf 'Stopping %s for user %s\n' "$service" "$user"
      systemctl --user --machine="$user"@.host stop "$service"
    fi
  done
}

pre_upgrade() {
  ## arg 1:  the new package version
  ## arg 2:  the old package version

  if (( "$(vercmp "$2" '1:7.0.4-1')" < 0 )); then
    _compare_config_notice
  fi

  if (( "$(vercmp "$2" '1:7.0.0-1')" < 0 )); then
    printf 'NOTE: Major changes introduced for mounting and unmounting!\n'
    _stop_user_unit_for_logged_in_users "$default_service"
    _compare_config_notice
  fi
}

pre_remove() {
  ## arg 1:  the old package version

  _stop_user_unit_for_logged_in_users "$default_service"
}
