#!/bin/sh
# Container entrypoint that handles the common bind-mount-as-root case.
#
# When volumes are bind-mounted into the container (e.g. `-v ./data/isos:...`),
# they come up owned by the host uid:gid — often root:root. The openpxe
# binary runs as uid 10001 and can't write there. This script, when started
# as root, chowns the two state dirs to the openpxe user, then drops
# privileges via gosu before execing the binary.
#
# If the container is already running as non-root (OpenShift does this via
# its own uid assignment from the SCC), we skip the chown attempt and just
# exec the binary — OpenShift either preconfigures the volume with fsGroup
# or the operator is on their own for permissions.
set -e

OPENPXE_UID=${OPENPXE_UID:-10001}
OPENPXE_GID=${OPENPXE_GID:-10001}
DATA_DIRS="/var/lib/openpxe/isos /var/lib/openpxe/work /var/lib/openpxe/smb"

if [ "$(id -u)" = "0" ]; then
    for d in $DATA_DIRS; do
        if [ -d "$d" ]; then
            chown -R "${OPENPXE_UID}:${OPENPXE_GID}" "$d" 2>/dev/null || true
        fi
    done
    # Re-exec ourselves under the openpxe user so the binary inherits a
    # clean process environment and a predictable umask.
    exec gosu "${OPENPXE_UID}:${OPENPXE_GID}" /usr/local/bin/openpxe "$@"
fi

# Non-root: straight exec, no chown attempt.
exec /usr/local/bin/openpxe "$@"
