#!/bin/sh

if test $(id -u) -ne 0
then
    echo 'This must be run as root.'
    exit 1
fi

write_profile() {
    test -f $1 || touch $1 && chown $uid:$gid $1
    if ! grep -q '# lxc-users-setup' $1
    then
        echo 'for i in /sys/fs/cgroup/*/$USER/tasks; do test -w $i && echo $$ > $i; done # lxc-users-setup' >> $1
    fi
}

for i in $(awk '!/^#/{if($1!~"@"){print$1}}' /etc/lxc/lxc-usernet)
do
    passwd=$(getent passwd $i)
    user=$(echo $passwd | cut -d : -f 1)
    uid=$(echo $passwd | cut -d : -f 3)
    gid=$(echo $passwd | cut -d : -f 4)
    home=$(echo $passwd | cut -d : -f 6)
    test -f '/etc/subuid' || touch '/etc/subuid'
    if ! grep -qE "^($user|$uid):100000:65536\$" '/etc/subuid'
    then
        usermod -V 0-4294967295 -v 100000-165535 $user
    fi
    test -f '/etc/subgid' || touch '/etc/subgid'
    if ! grep -qE "^($user|$uid):100000:65536\$" '/etc/subgid'
    then
        usermod -W 0-4294967295 -w 100000-165535 $user
    fi
    write_profile $home/.bash_profile
    write_profile $home/.zprofile
    if ! test -f $home/.config/lxc/default.conf
    then
        mkdir -p $home/.config/lxc
        echo 'lxc.include = /etc/lxc/default.conf' > $home/.config/lxc/default.conf
        chown $uid:$gid $home/.config $home/.config/lxc $home/.config/lxc/default.conf
    fi
done
