#!/bin/bash
# ITC-2986 keep all environment variables for config generation inside of docker containers
# ITC-3780 Replace sudo with runuser
# On the SAT we have to use a mix of runuser and sudo - as we have non root users (nagios, NSTA) wo needs to be able to execute the "oitc" command
if [ "$(id -u)" -eq 0 ]; then
    # We are already root, so we can use runuser and switch to the www-data group
    exec runuser -u root -g www-data -- /opt/openitc/frontend/bin/cake "$@"
    # runuser: only root can specify alternative groups
else
    # We are not root, so we can use sudo to switch to the www-data group
    # This is used by the NSTA (nagios user) to run cake commands as www-data to not have permission issues with tmp files.
    # As it is not important to keep any environment variables when the NSTA runs the command, wo ignore the --preserve-env shenanigans for now.
    sudo -g www-data /opt/openitc/frontend/bin/cake "$@"
fi

#exec sudo -g www-data /opt/openitc/frontend/bin/cake "$@"

# 18.12.2025 - We have to revert the --preserve-env as it makes issues with the NSTA
# sudo: sorry, you are not allowed to preserve the environment
#
#
# ITC-2986 keep all environment variables for config generation inside of docker containers
##preserveEnvSupportsList=$(sudo --help |grep "preserve-env" | wc -l)
##if [[ $preserveEnvSupportsList -gt 1 ]]; then
##    sudo -g www-data --preserve-env=OITC_DEBUG /opt/openitc/frontend/bin/cake "$@"
##else
    # Old sudo version that does not support list of environment variables to preserve
    # Added with 9bb78048656f 2017-08-03
#    sudo -g www-data --preserve-env /opt/openitc/frontend/bin/cake "$@"
##fi
