#!/bin/sh
# Copyright (C) 2012 Jolla Oy
# Contact: Pekka Lundstrom  <pekka.lundstrom@jollamobile.com>
#
# This adds default user (1000) to group provided as $1
# Group needs to exist before calling this
# If user with default id does not exist, 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" ] || 
   [[ "$PATH" != *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
DEF_UID=$(grep "^UID_MIN" /etc/login.defs |  tr -s " " | cut -d " " -f2)
DEVICEUSER=$(getent passwd $DEF_UID | sed 's/:.*//')
if [ -n "$DEVICEUSER" ]; then
    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
ln -sf /usr/lib/oneshot.d/groupadd-user.later /etc/oneshot.d/0/
