#!/bin/bash

# This script either runs a given command using bash directly, or if YBOX_HOST_UID environment
# variable is set to something other than the UID of the current user, then uses sudo to run
# the command as that UID (plus YBOX_HOST_GID as the GID). This latter case happens for rootless
# docker where the ybox container runs as the root user (due to absence of --userns=keep-id like
#   in podman) but some commands need to be run as a normal user like Arch's paru/yay AUR helpers.

set -e

if [ "$#" -ne 1 ]; then
  echo "Usage: $0 <full command to run as single argument like passed to '/bin/bash -c'>"
  exit 1
fi

if [ "$(id -u)" -eq 0 -a -n "$YBOX_HOST_UID" ] && getent passwd $YBOX_HOST_UID > /dev/null; then
  sudo -u "#$YBOX_HOST_UID" -g "#$YBOX_HOST_GID" /bin/bash -c "$1"
  status=$?
  if [ $status -ne 0 ]; then
    echo "FAILED (exit code = $status) in sudo execution of: $1"
    exit $status
  fi
else
  eval "$1"
  status=$?
  if [ $status -ne 0 ]; then
    echo "FAILED (exit code = $status) in execution of: $1"
    exit $status
  fi
fi
