#!/bin/sh

check_rootless() {
    if [ "$EUID" -eq 0 ]; then
        printf 'You cannot run this script as root\n'
        exit 0
    fi
}

check_rootless

lev=$(pdp-id -l)
ilev=$(pdp-id -i)
cat=$(pdp-id -c)

user="$(id -un)"
label="${lev}:${ilev}"

service_escaped="rootless-docker@$(systemd-escape "${user}@${label}")"
service_plain="rootless-docker@${user}@${label}"

CONFIG_FILE=/etc/rootless-helper-astra.conf
if test -f $CONFIG_FILE; then
    source $CONFIG_FILE
fi
if [ -z $ROOTLESS_DOCKER_ROOT ]; then
    ROOTLESS_DOCKER_ROOT=/var/lib/rootlessdocker
fi

rootless_home=$ROOTLESS_DOCKER_ROOT/$USER/l${lev}i${ilev}c${cat}t0x0
run_name=rootless-run

export XDG_RUNTIME_DIR=$rootless_home/$run_name

if [ -z "$XDG_RUNTIME_DIR" ] || [ ! -d "$XDG_RUNTIME_DIR" ]; then
    echo "Error: no files found at path $XDG_RUNTIME_DIR. This may be because the service $service_plain is not running."
    exit 1
fi

# Проверяем доступ к systemctl list-units
if systemctl list-units --type=service "$service_escaped" >/dev/null 2>&1 || \
   systemctl list-units --type=service "$service_plain" >/dev/null 2>&1; then
    # Если доступ есть, проверяем активность сервисов
    if ! systemctl list-units --type=service "$service_escaped*" 2>/dev/null | grep -q running && \
       ! systemctl list-units --type=service "$service_plain*" 2>/dev/null | grep -q running; then
        echo "Warn: The service with the template name $service_plain is not found or not running."
    fi
fi


export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker/docker.sock
export ROOTLESS_HELPER=1
export ROOTLESS_HELPER_VERSION=0.1.18
export PATH=/sbin:$PATH
export TMPDIR=$rootless_home/tmp
export PS1="rootless >> ${debian_chroot:+($debian_chroot)}\u@\h:\w\$ "

if test -z "$*"; then
    /bin/sh
else
    "$@"
fi
