#!/bin/bash
# ------------------------------------------------------------------
# AUTHOR: [LucidLink Support]
# NAME: sso_permissions_script.sh
# VERSION: 2.0
# DESCRIPTION: Single sign-on permissions/shares import script. 
# Creates permissions/shares from backup substituting Azure/Okta 
# SSO providers.
#
# THE SCRIPT IS PROVIDED “AS IS” AND “AS AVAILABLE” AND IS WITHOUT
# WARRANTY OF ANY KIND. PLEASE REVIEW ALL TERMS AND CONDITIONS.
# https://www.lucidlink.com/legal-documents
# ------------------------------------------------------------------

IFS=";"
USAGE="Usage: ./sso_permissions_script.sh <password>
Request failed with: Bad Request
Empty required parameter 'password' is not allowed!"
PERMISSIONVER="2.2"
FSFORMAT1="$(lucid status | grep "Filespace format:" | cut -f 2 -d \: | sed "s/ //g")"

# --- Ensure password ---
if [ $# -lt 1 ] ; then
    echo "$USAGE"
    exit 1;
fi

# --- Identify Filespace format --- 
if [ $(echo "$PERMISSIONVER > $FSFORMAT1"|bc -l) -eq 1 ];
  then COMMAND1="share"; COLUMN="SHAREPATH;USERGROUP;TYPE;SHAREDAS;PERMISSIONS"; OPTION1="--permissions";
  else COMMAND1="permission"; COLUMN="SHAREPATH;USERGROUP;TYPE;PERMISSIONS"; OPTION1="--access"
fi

# ---  Ensure Backup exists ---
BACKUPFILE="sso_""$COMMAND1""s_backup.txt"
if test -f "$BACKUPFILE" ;
    then :
else
    echo -e "\e[31mError: your $BACKUPFILE backup file does not exist make sure to backup your configuration exactly as instructed in Step 1.\e[0m"    
	exit 1
fi

# --- Loop through permissions/shares backup excluding Lucid users and substitute SSO provider ---
cat "$BACKUPFILE" | sed -e 's/ \{2,\}/;/g;s/\[user\]/;user/g;s/\[group\]/;group/g;s/okta\\/sso\\/g;s/azure\\/sso\\/g;s/ ;/;/g;s/read, write/read,write/g' | grep -v 'lucid\\' | grep 'sso\\' > sso_permissions_import.txt
while read -r $COLUMN; do
  SHARESET=("lucid $COMMAND1 --set '$SHAREPATH' --$TYPE '$USERGROUP' $OPTION1 $PERMISSIONS --password '$1'")
  echo "$SHARESET" >> sso_permissions_commands.txt
  eval $SHARESET 2>&1 | tee -a sso_permissions_output.txt
done < sso_permissions_import.txt

exit