#!/bin/bash
# ------------------------------------------------------------------
# AUTHOR: [LucidLink Support]
# NAME: permissions_script.sh
# VERSION: 2.0
# DESCRIPTION: Lists permissions/shares from Filespace instance 1 
# and imports into Filespace instance 2
#
# 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: ./permissions_script.sh <fs1rootpwd> <fs2rootpwd>
Request failed with: Bad Request
Empty required parameter 'password' is not allowed!"
PERMISSIONVER="2.2"
FSFORMAT1="$(lucid --instance 1 status | grep "Filespace format:" | cut -f 2 -d \: | sed "s/ //g")"
FSFORMAT2="$(lucid --instance 2 status | grep "Filespace format:" | cut -f 2 -d \: | sed "s/ //g")"

# --- Ensure password ---
if [ $# -lt 2 ] ; 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";
  else COMMAND1="permission"; COLUMN="SHAREPATH;USERGROUP;TYPE;PERMISSIONS";
fi
if [ $(echo "$PERMISSIONVER > $FSFORMAT2"|bc -l) -eq 1 ];
  then COMMAND2="share"; OPTION2="--permissions";
  else COMMAND2="permission"; OPTION2="--access";
fi

# --- List instance 1 permissions/shares assignments, apply users and groups permissions/shares within instance 2 ---
lucid --instance 1 $COMMAND1 --configured --password ''$1'' | sed -e 's/ \{2,\}/;/g;s/\[user\]/;user/g;s/\[group\]/;group/g;s/ ;/;/g;s/read, write/read,write/g' | grep 'lucid\\' > lucid_permissions.txt
while read -r $COLUMN; do
  SHAREASSIGN=("lucid --instance 2 $COMMAND2 --set '$SHAREPATH' --$TYPE '$USERGROUP' $OPTION2 $PERMISSIONS --password '$2'")
  echo "$SHAREASSIGN" >> lucid_permissions_commands.txt
  eval $SHAREASSIGN 2>&1 | tee -a lucid_permissions_output.txt
done < lucid_permissions.txt

exit
