#!/bin/bash
# script creates home directories for users in rgroup if those do not exist

set -e
# set -x
# trap read debug


rgroup="g_r_users"
localrgroup="local_r_users"
home="/homes/"
work="/work/"
rstudiodir=".rstudio"
umask=0077
skel="/etc/skel"
monitoringuser="monitoring"

if [ ! -d $home ]
  then
    mkdir $home
fi

# make sure that fresh credentials are pulled
/usr/sbin/sss_cache -E

unset rusers
rusers="$(getent group $rgroup | awk -F '[/:]' '{print $4}')"
rusers="$rusers,$(getent group $localrgroup | awk -F '[/:]' '{print $4}')"
IFS=$',' read -r -a ruserar <<< "$rusers"
for ruser in "${ruserar[@]}"
  do
    # create home directories
    if [ ! -d "$home$ruser" ]
      then
        /sbin/mkhomedir_helper "$ruser" "$umask" "$skel"
        setfacl  -m u:$monitoringuser:rx "$home$ruser"
    fi
    # symlink .rstudio directory to work storage
    if [ ! -d "$work$ruser/$rstudiodir" ]
      then
        mkdir -m 770 -p "$work$ruser"
        mkdir -p "$work$ruser/$rstudiodir"
        mkdir -p "$home$ruser/$rstudiodir"
        setfacl  -m u:"$monitoringuser":rx "$work$ruser"
        setfacl  -m u:"$monitoringuser":rx "$work$ruser/$rstudiodir"
        seufacl  -m u:"$ruser":rwx "$work$ruser"
        setfacl  -m u:"$ruser":rwx "$work$ruser/$rstudiodir"
        mount --bind "$work$ruser/$rstudiodir" "$home$ruser/$rstudiodir"
        #ln -s $work$ruser/$rstudiodir $home$ruser/$rstudiodir
        #chattr +i $home$ruser/$rstudiodir
    fi
done
unset IFS
