#!/bin/bash

# Assume we run without the wrapper by default.
USE_CGROUP_WRAPPER=false

# Check if the --enduser_backup flag is passed.
for arg in "$@"; do
	
	# If it is, check if either cgroup v1 or v2 is available.
	if [[ "$arg" == "--enduser_backup" || "$arg" == "--enduser_restore" || "$arg" == "--master_download" || "$arg" == "--download" ]]; then
		if [[ (-f /sys/fs/cgroup/cgroup.controllers || ( -d /sys/fs/cgroup/cpu && -d /sys/fs/cgroup/memory && -d /sys/fs/cgroup/blkio )) && -f /var/backuply/conf/resource_limits_enabled ]]; then
			
			USE_CGROUP_WRAPPER=true
			
		fi
		
		# Since we found the flag, we can stop looping.
		break
	fi
done

# Check if unshare is available and we are root to hide mounts from host (especially for cPanel)
UNSHARE_CMD=""
if [[ "$EUID" -eq 0 ]] && command -v unshare >/dev/null 2>&1; then
	UNSHARE_CMD="unshare -m --propagation private"
fi

# Use the cgroup wrapper. The wrapper itself will handle v1/v2 differences.
if [[ "$USE_CGROUP_WRAPPER" == true ]]; then

	$UNSHARE_CMD /usr/local/backuply/bin/backuply-cgroup /usr/local/backuply/bin/php /usr/local/backuply/cli.php "$@"

# Run the command directly without the wrapper.
else
    $UNSHARE_CMD /usr/local/backuply/bin/php /usr/local/backuply/cli.php "$@"
fi