#!/usr/bin/env bash

set -e
set -o pipefail

PACKAGE="$1"

if [ -z "$PACKAGE" ]; then
  echo "usage: $0 <package>"
  echo ""
  exit 1
fi

if [ -z "${OPENNMS_HOME}" ]; then
  # shellcheck disable=SC2016,SC2154
  OPENNMS_HOME='${install.dir}'
fi

if [ -e "${OPENNMS_HOME}/etc/opennms.conf" ]; then
  # shellcheck disable=SC1090,SC1091
  . "${OPENNMS_HOME}/etc/opennms.conf"
fi
[ -z "$RUNAS" ] && RUNAS=opennms

if ! id -u "${RUNAS}" >/dev/null 2>&1; then
  echo "Something is very wrong, \$RUNAS=${RUNAS} but that user does not exist. Bailing."
  exit 1
fi

if [ "${RUNAS}" != "opennms" ]; then
  printf '$RUNAS has been changed from the default "opennms" user. Assuming you know what you are doing and changing ownership of files to "%s".\n\n' "${RUNAS}"
fi

RUNAS_UID="$(id -u "${RUNAS}" 2>/dev/null || :)"
RUNAS_GID="$(id -g "${RUNAS}" 2>/dev/null || :)"

if [ -z "${RUNAS_UID}" ] || [ -z "${RUNAS_GID}" ]; then
  echo "ERROR: unable to determine UID and GID from \$RUNAS=${RUNAS}. Bailing."
  exit 1
fi

SUDO="$(command -v sudo 2>/dev/null || which sudo 2>/dev/null || :)"

do_sudo() {
  if [ "$(id -u -n)" = "root" ]; then
    # If we already are root, no need for sudo
    "$@"
  elif [ -x "$SUDO" ]; then
    "$SUDO" "$@"
  else
    # if no sudo, fall back to running as the current user
    echo "WARNING: sudo was not located, but this script is not being run as root. This will probably fail."
    "$@"
  fi
}

# shellcheck disable=SC2086
(if [ -e /etc/debian_version ]; then
  dpkg --listfiles "$PACKAGE";
elif [ -e /etc/redhat-release ]; then
  rpm -ql "$PACKAGE";
fi) | grep /opennms | do_sudo xargs --no-run-if-empty -d '\n' chown "${RUNAS_UID}:${RUNAS_GID}"

if [ ! -e /etc/debian_version ] && [ ! -e /etc/redhat-release ]; then
  echo "WARNING: not a Debian/Ubuntu or RedHat system -- check the contents of $OPENNMS_HOME is owned by $RUNAS."
fi
