#!/bin/bash -e

# The script will receive 5 parameters from octofussd, in this order:

# The share name (the directory will be /home/SAMBA/<name_of_the_share>)
# Guest ok (as 'yes' or 'no' string)
# Read only (as 'yes' or 'no' string)
# Read list (as a string of group names, comma separated)
# Write list (as a string of group names, comma separated)

# refs #14440
# Set the permissions on the /home/SAMBA/<name_of_the_share> directory

## uncomment the following to get debug print on a temporary file,
## NOTE: because octofussd run with PrivateTmp=true, the file will
## be created under something like:
## /tmp/systemd-private-*-octofussd.service-*/
#DEBUG=yes
LOGFILE=/tmp/octofuss-samba-shares.log

if [ -n "$DEBUG" ]; then
   exec  >> $LOGFILE 2>&1
   echo Executed on $(date)
   echo Parameters:
   echo '================='
   echo Share name: $1
   echo Guest ok: $2
   echo Read only: $3
   echo Read list: $4
   echo Write list: $5
   echo '================='
fi

#
SHARE=$1
DIRECTORY=/home/SAMBA/$SHARE

# put groups in array from arguments
echo $4 | IFS=',' read -ra READGROUPS
echo $5 | IFS=',' read -ra WRITEGROUPS
IFS=',' read -ra READGROUPS <<< $4
IFS=',' read -ra WRITEGROUPS <<< $5

if [ "$2" == "yes" ]; then
    chmod 755 $DIRECTORY
else
    chmod 750 $DIRECTORY
fi

setfacl -b $DIRECTORY

for i in "${READGROUPS[@]}"; do
    if [ -n "$DEBUG" ]; then
	echo read group $i
    fi
    setfacl -m "g:$i:rx" $DIRECTORY
done
for i in "${WRITEGROUPS[@]}"; do
    if [ -n "$DEBUG" ]; then
	echo write group $i
    fi
    setfacl -m "g:$i:rwx" $DIRECTORY
done

exit 0
