#!/bin/bash
# By MB
# Add subuids and subgids for a non root user

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

if [ $# -ne 1 ]; then
    echo "$0 [USERNAME]"
else
    echo "Checking if the user exists ..."
    getent passwd "$1" || (echo "no user $1": exit 1)
    user="$1"
    # Check if the user has uids?
    grep -F "$user" /etc/subuid && (echo "User exists already"; exit 1)
    # get the last number
    lastentry=$(cat /etc/subuid | sort -t ':' -k 2 -n | 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)) "$user"
    # Check again!
    grep "$user" /etc/subuid
    echo "Please run podman system migrate to make changes work"
fi
