#!/bin/bash
#
# Copyright (C) 2015-2025  it-novum GmbH
# Copyright (C) 2025-today AVENDIS GmbH
#
# This file is dual licensed
#
# 1.
#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, version 3 of the License.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# 2.
#     If you purchased an openITCOCKPIT Enterprise Edition you can use this file
#     under the terms of the openITCOCKPIT Enterprise Edition license agreement.
#     License agreement and license key will be shipped with the order
#     confirmation.
#

# ITC-2986 keep all environment variables for config generation inside of docker containers
# ITC-3780 Replace sudo with runuser
# ITC-3832 Replace runuser with setpriv as it does not fiddle around with PAM or the environment
# In case we run as Cronjob, we set the PATH variable. Otherwise CakePHP will may not find some commands
export PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Find GID of the www-data group, because older setpriv versions do not support group names, only GIDs.
WWW_GID="$(getent group www-data | cut -d: -f3)"
if [[ -z "$WWW_GID" || "$WWW_GID" == "0" ]]; then
    echo "ERROR: could not resolve a valid GID for group www-data (got: '${WWW_GID:-<empty>}')" >&2
    exit 78
fi

# Make sure new created files are group writable, so that the webserver can overwrite them.
umask 002

# Exec the command, preserve the environment and change the group to www-data
exec setpriv --reuid 0 --regid "$WWW_GID" --keep-groups -- /opt/openitc/frontend/bin/cake "$@"

