#!/bin/sh
# Copyright (c) 2012 - 2019 Jolla Ltd.
# Copyright (c) 2019 - 2020 Open Mobile Platform LLC.
#
# This adds current user to group provided as $1
# Group needs to exist before calling this
# If user is not found, this will schedule
# new run after next boot
# This script can also be called with $2 as --no-later
# then later scheduling is not done

[ -z "$1" ] && exit 1
GROUP=$1

# Define PATH in case we are called in build time (PATH empty or sbin not included)
if [ -z "$PATH" ] || echo "$PATH" | grep -q sbin; then
    PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
fi

getent group $GROUP > /dev/null || exit 2
if [ -f "/.bootstrap" ]; then
    DEF_UID=$(grep "^UID_MIN" /etc/login.defs |  tr -s " " | cut -d " " -f2)
    DEVICEUSER=$(getent passwd $DEF_UID | sed 's/:.*//')
else
    DEVICEUSER=$(loginctl list-sessions | grep seat0 | tr -s " " | cut -d " " -f 4)
fi
if [ -n "$DEVICEUSER" ]; then
    [ -f "/.bootstrap" ] && echo "Bootstrap: Adding user $DEVICEUSER to group $GROUP"
    getent group $GROUP | grep -q $DEVICEUSER && exit 0
    usermod -G $GROUP -a $DEVICEUSER && exit 0
fi

# We couldn't add group for the user at this time. We schedule it for next boot
[ -n "$2" ] && [ "$2" = "--no-later" ] && exit 0
touch /etc/oneshot.d/group.d/$GROUP
mkdir -p /etc/oneshot.d/0
ln -sf /usr/lib/oneshot.d/groupadd-user.later /etc/oneshot.d/0/
