#!/bin/bash
# By MB
# Add a podman manager user

if [ $EUID -ne 0 ]; then
    echo "Please run as root!"
    exit 1
fi

pause(){
    read -n1 -rsp $'Press any key to continue or Ctrl+C to exit...\n'
}

# First we can check if we have cgroup v2 or v1
echo "Cgroup v1 is default, Cgroup v2 allows resource control"
if ! mount -l | grep cgroup2;
then
    if ! grep unified /etc/default/grub;
    then
        read -rp "Add cgroup v2 to grub (y/n) " arg
        if [ "$arg" == "y" ]; then
            grubby --update-kernel=ALL --args="systemd.unified_cgroup_hierarchy=1"
        fi
    fi
fi

# Create a configuration to allow user resource control
if [ ! -f /etc/systemd/system/user@.service.d/delegate.conf ]; then
    mkdir -p /etc/systemd/system/user@.service.d
    cat <<EOF | sudo tee /etc/systemd/system/user@.service.d/delegate.conf
[Service]
Delegate=yes
DelegateControllers=cpu cpuset io memory pids
EOF
fi
# only works if cgroup2 is present:
echo Found cgroup v2 controlable resources:
cat /sys/fs/cgroup/cgroup.subtree_control

echo Available cgroup:
mount -l | grep cgroup
echo ---

# did you give a username?
if [ $# -ne 1 ]; then
    read -rp "Podman manager user (e.g. podbot): " NEWUSER
    if [ -z "$NEWUSER" ]; then
        echo "nothing provided?"
        NEWUSER=podbot
    fi
else
    NEWUSER="$1"
fi
echo "using podman manager name: $NEWUSER"
if ! grep "$NEWUSER" /etc/passwd;
then
    pause
    useradd "$NEWUSER"
fi

# needs a subuid for podman rootless containers
if ! grep "$NEWUSER" /etc/subuid;
then
    echo "Need to create a subuid"
    pause
    # get the last number
    lastentry=$(sort -t ':' -k 2 -n /etc/subuid | tail -n1)
    idmax=$(echo "$lastentry" | awk -F: '{print $2}')
    idmax_range=$(echo "$lastentry" | awk -F: '{print $3}')
    idmax=$((idmax + idmax_range))
    # add the new subuid range
    usermod -v ${idmax}-$((idmax + 65536)) -w ${idmax}-$((idmax + 65536)) "$NEWUSER"
    echo "Created new sub uid: ${idmax}-$((idmax + 65536)) -w ${idmax}-$((idmax + 65536))"
fi
grep "$NEWUSER" /etc/subuid || (echo "still no subuid for $NEWUSER"; exit 1)
echo enabling lingering of user account.
loginctl enable-linger "$NEWUSER"

echo ---
echo Check Cgroup controll groups:
cat "/sys/fs/cgroup/user.slice/user-$(id -u $NEWUSER).slice/user@$(id -u $NEWUSER).service/cgroup.controllers"
echo ---
#
# Activate the podman socket
# 
echo "Activating $NEWUSER system service + podman socket"
pause
# $UID will be expanded inside the user shell
su - "$NEWUSER" bash -c 'XDG_RUNTIME_DIR=/run/user/$UID systemctl enable --user podman.socket'
su - "$NEWUSER" bash -c 'XDG_RUNTIME_DIR=/run/user/$UID systemctl start --user podman.socket'
su - "$NEWUSER" bash -c 'podman system migrate'
su - "$NEWUSER" bash -c 'podman run --rm hello-world'
echo "done"
# Done