#!/usr/bin/bash

. /usr/share/restraint/plugins/helpers

rstrnt_info "*** Running Plugin: $0"

_is_rhfamily() {
  local family="$1"
  local op="$2"
  local ver="$3"
  shift 3
  local the_rpms
  if rpm -q --whatprovides redhat-release &>/dev/null; then
    the_rpms="$(rpm -q --whatprovides redhat-release)"
  elif rpm -q --whatprovides fedora-release &>/dev/null; then
    the_rpms="$(rpm -q --whatprovides fedora-release)"
  else
    return 1
  fi
  local the_fam="$(rpm -q --qf="%{NAME}" $the_rpms)"
  the_fam="${the_fam%%-*}"
  local the_ver="$(rpm -q --qf="%{VERSION}" $the_rpms | sed "s/^\([0-9]\+\)[^0-9]\+.*$/\1/")"
  if [[ "$op" == "show" ]]; then
    rstrnt_debug "Family: $the_fam"
    rstrnt_debug "Version: $the_ver"
    rstrnt_debug "Rpms: $the_rpms"
    return 0
  fi
  [ "$the_fam" = "$family" ] && [ "$the_ver" "$op" "$ver" ]
}
is_rhel() { _is_rhfamily redhat "$1" "$2"; }
is_fedora() { _is_rhfamily fedora "$1" "$2"; }
is_centos() { _is_rhfamily centos "$1" "$2"; }

function _runcon_unconfined_cmd() {
  # Determine correct SELinux context for runcon
  local suser='root'
  local srole='system_r'
  local stype='unconfined_t'
  local additional='-l s0'
  if is_rhel -ge 6 || is_fedora -ge 12; then
    suser='unconfined_u'
    srole='unconfined_r'
    additional='-l s0-s0:c0.c1023'
  elif is_rhel -le 4; then
    additional=''
  fi
  echo runcon -u $suser -r $srole -t $stype $additional
}

function runcon_unconfined() {
  local runcon_cmd=$(_runcon_unconfined_cmd)
  if runcon 2>/dev/null | grep -q "unconfined_u:unconfined_r:unconfined_t:"; then
    # Already in the desired context
    exec "$@"
  elif $runcon_cmd -- true; then
    # Run command with SELinux context of the root
    exec $runcon_cmd -- "$@"
  else
    rstrnt_info "'$runcon_cmd -- true' failed. Running in default context."
    exec "$@"
  fi
}

if command -v selinuxenabled >/dev/null && selinuxenabled; then
  if [ 4 -le 0$RSTRNT_DEBUG ]; then
      rstrnt_info "selinux enabled: trying to switch context..."
  fi
  runcon_unconfined "$@"
else
  exec "$@"
fi
