#!/usr/bin/bash
#
# Simple helper to set up subuid / subgid for the first
# user in the sudo group

set -euo pipefail

GROUP=sudo
SUBUID_RANGE="524288-589823"
SUBGID_RANGE="524288-589823"

if [ -s /etc/subuid ] || [ -s /etc/subgid ]; then
    # Already configured
    exit 0
fi

user=$(getent group "$GROUP" | awk -F: '{ print $4 }')

if [ -z "${user}" ]; then
    # No sudo user yet, nothing to do
    exit 0
fi

if [[ "${user}" =~ "," ]]; then
    # More than one sudo user
    exit 0
fi

echo "Setting up /etc/sub{u,g}id for $user"

usermod --add-subuids ${SUBUID_RANGE} "${user}"
usermod --add-subgids ${SUBGID_RANGE} "${user}"
