#!/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 "${SENTINEL_HOME}" ]; then
  # shellcheck disable=SC2016,SC2154
  SENTINEL_HOME='/root/project/target/sentinel-29.0.3'
fi

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

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}" != "sentinel" ]; then
  echo "\$RUNAS has been changed from the default 'sentinel' user. Assuming you know what you're doing and _not_ changing ownership of any files."
  echo ""
  exit 0
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 [ -x "$SUDO" ]; then
    "$SUDO" "$@"
  else
    # if no sudo, fall back to running as the current user
    if [ "$(id -u -n)" != "root" ]; then
      echo "WARNING: sudo was not located, but this script is not being run as root. This will probably fail."
    fi
    "$@"
  fi
}

# shellcheck disable=SC2086
(if [ -e /etc/debian_version ]; then
  dpkg --listfiles "$PACKAGE";
elif [ -e /etc/redhat-release ]; then
  rpm -ql "$PACKAGE";
fi) | grep /sentinel | do_sudo xargs -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 $SENTINEL_HOME is owned by $RUNAS."
fi
