#!/bin/bash

## This example demonstrates how to create a FTP network storage using the server API.
echo -e '\n';
echo "##########################################################################################################"
echo "This example demonstrates how to replace a physical path with network storage for user accounts and groups."
echo "##########################################################################################################"


### Read from the user
echo -e '\n';
echo "#######################"
echo "Enter Basic Parameters"
echo "######################"
echo "Enter protocol:"
read proto
echo "Enter server REST host:"
read jscapehost
echo "Enter server REST port:"
read jscapemanagmentport
echo "Enter REST username:"
read username
echo "Enter REST password:"
read password
echo "Enter domain name:"
read domain
echo "Select the OS where physical path exists ?:"
select oType in "Windows" "Linux";
do
    echo "OS: $oType"
    break
done

## format user input for search operation as linux contains back slash to be as escapes
if [[ "$oType" = "Windows" ]];then
echo -e '\n';    
echo "!!! Make a note on the path from MFT Server before input !!!"
echo -e '\n';    
echo "Enter the physical path to replace: eg 1; c:\\\\test\\\\test2 (in MFT - c:\\test\\test2) eg 2: c:\\\\test\\\\test3\\\\ (in MFT - c:\\test\\test2\\test3\\)"
read path
wPath=$(echo $path | sed 's/\\/\\\\/gI' > wpath.txt)
path=$(cat wpath.txt | sed 's/\\/\\\\/gI')
## is valid path check for windows
if [[ "$path" != "%installdir%/users/%domain%/%username%" ]]; then
while true; do 
 if [[ "$path" =~ '/' || -z "$path" ]]; then
     echo "Invalid path, enter valid path for Windows !!! "
     read path
     continue
 else 
     break
 fi        
done
fi
fi 

if [[ "$oType" = "Linux" ]];then
echo -e '\n';    
echo "!!! Make a note on the path from MFT Server before input !!!"
echo -e '\n';       
echo "Enter the physical path to replace: eg 1; /Users/test eg 2; /Users/test1/test2/"
read path
## is valid path check for linux
if [[ "$path" != "%installdir%/users/%domain%/%username%" ]]; then
while true; do 
 if [[ "$path" =~ '\' || "$path" =~ ':' || -z "$path" ]]; then
     echo "Invalid path, enter valid path for Linux !!! "
     read path
     continue
 else 
     break
 fi        
done
fi
fi 

echo "Enter the destination network storage name:"
read s3name

### make a cookie file to store the session id and get it through get_session_id()
cookie_file=`mktemp /tmp/cookie.XXXXXXXXXX`

get_session_id() {
   grep JSESSIONID $cookie_file | awk '{printf "%s=%s",$6,$7}'
}

## get CSRF token
csrftoken=`curl -s -k -c "${cookie_file}" -H "Content-type: application/json" $proto://$jscapehost:$jscapemanagmentport/rest/management/csrf-token`

### get session cookie
sid=$(get_session_id ${cookie_file})


## Login to MFT Server
loginResponse=$(curl -s -k -b "$sid" -c "$cookie_file" -w "%{http_code}" -o /dev/null -H "accept: */*" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "Content-type: application/json" -X POST -d "{\"username\":\"$username\", \"password\":\"$password\"}" $proto://$jscapehost:$jscapemanagmentport/rest/management/login)

## check server reachable
if [[ "$loginResponse" -eq 000 ]]; then 
echo -e '\n';
echo "Could not connect to the server ..";  
else

if [[ "$loginResponse" -eq 204 ]]; then 
echo -e '\n';
echo "Login success .. Processing input ..";  

### get session cookie again
sid=$(get_session_id ${cookie_file})

## get CSRF token again
csrftoken=`curl -s -k -b "$sid" -H "Content-type: application/json" $proto://$jscapehost:$jscapemanagmentport/rest/management/csrf-token`

## Check if domain exists
while true; do
    getDomainResponse=$(curl -s -k -b "$sid" -o accounts.txt -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X GET $proto://$jscapehost:$jscapemanagmentport/rest/management/domains/$domain)
    if [[ "$getDomainResponse" -eq 404 ]]; then
        echo "Domain does not exist, enter valid name .."
        read domain
        continue
    else
        break
    fi
done

## Check if amazon s3 storage exists
while true; do
    getStorageResponse=$(curl -s -k -b "$sid" -o accounts.txt -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X GET $proto://$jscapehost:$jscapemanagmentport/rest/management/reverse-proxies/$domain/$s3name)
    if [[ "$getStorageResponse" -eq 404 ]]; then
        echo "Network storage does not exist, enter valid name .."
        read s3name
        continue
    else
        break
    fi
done

if [[ "$getStorageResponse" -eq 200 && "$getDomainResponse" -eq 200 ]]; then

## Accounts -- Start

## get all accounts and save it to a file
getAccountsResponse=$(curl -s -k -b "$sid" -o accounts.txt -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X GET $proto://$jscapehost:$jscapemanagmentport/rest/management/account-service/$domain/names)


## success block for get account list api call
if [[ "$getAccountsResponse" -eq 200 ]]; then 
echo -e '\n';
echo "##################################################################";  
echo "Processing the Users/Accounts module for " $domain " -- Started"
echo "##################################################################"; 

## loop and update all user accounts
value=$(<accounts.txt)
accounts=$(echo $value | tr "," "\n")
for account in $accounts
do
## format account login and check account availability    
accountLogin=$(echo $account | sed 's/[][]//g' | sed 's/["]//g')
getAccountResponse=$(curl -s -k -b "$sid" -o $accountLogin.json -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X GET $proto://$jscapehost:$jscapemanagmentport/rest/management/accounts/$domain/$accountLogin)

## success block for get account api call
if [[ "$getAccountResponse" -eq 200 ]]; then 
echo -e '\n';
echo "----------------------------------------------------------------------------------------------"  
echo "Check if path exists for account " $accountLogin " ?"

## Search and replace operation for S3 Storage on the account login json file  

if [[ "$oType" = "Linux" ]]; then
formatPath=$(echo $path | sed 's|\/|\\/|gI');
fi
if [[ "$oType" = "Windows" ]]; then
formatPath=$(cat wpath.txt | sed 's/\\/\\\\/gI')
fi  


if grep -qi -E "$formatPath($|\")" $accountLogin.json; then

echo "Input path found for account --> " $accountLogin


data=$(cat $accountLogin.json | sed "s|realPath\"\:\"$formatPath\"|name\"\:\"$s3name\"|gI")


getUpdateAccountResponse=$(curl -s -k -b "$sid" -o /dev/null -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X PUT -d "$data" $proto://$jscapehost:$jscapemanagmentport/rest/management/accounts/$domain/$accountLogin)

if [[ "$getUpdateAccountResponse" -eq 200 ]]; then  
echo "Updated the record for account --> " $accountLogin
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $accountLogin.json
fi
if [[ "$getUpdateAccountResponse" -eq 400 ]]; then  
echo "Update failed for account --> " $accountLogin
echo "Response code : 400 -- Bad Parameters"
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $accountLogin.json
fi
if [[ "$getUpdateAccountResponse" -eq 500 ]]; then  
echo "Update failed for account --> " $accountLogin
echo "Response code : 500 -- Bad Parameters"
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $accountLogin.json
fi
else
echo "Input path does not exist in account --> " $accountLogin " and nothing found to replace"
echo "----------------------------------------------------------------------------------------------"  
rm $accountLogin.json 
fi 
fi 
done 
echo -e '\n'; 
echo "##################################################################"; 
echo "Processing the Users/Accounts module for " $domain " -- Completed"
echo "##################################################################"; 
rm accounts.txt
fi

## failed creation check
if [[ "$getAccountsResponse" -eq 404 ]]; then 
echo -e '\n'; 
echo "Response Code : 404 -- Get account list call failed, Recheck the parameters.."  
rm accounts.txt
fi

## Accounts -- End

## Groups -- Start

## get all groups and save it to a file
getGroupsResponse=$(curl -s -k -b "$sid" -o groups.txt -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X GET $proto://$jscapehost:$jscapemanagmentport/2/rest/management/domains/$domain/group-names)

## success block for get groups api call
if [[ "$getGroupsResponse" -eq 200 ]]; then 
echo -e '\n'; 
echo "##################################################################"; 
echo "Processing the Groups module for " $domain " -- Started"
echo "##################################################################"; 

## loop and update all user groups
value=$(<groups.txt)
groups=$(echo $value | tr "," "\n")
for group in $groups
do
## format group and check group availability    
groupName=$(echo $group | sed 's/[][]//g' | sed 's/["]//g')
getGroupResponse=$(curl -s -k -b "$sid" -o $groupName.json -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X GET $proto://$jscapehost:$jscapemanagmentport/rest/management/groups/$domain/$groupName)

## success block for get group api call
if [[ "$getGroupResponse" -eq 200 ]]; then 
echo -e '\n';
echo "----------------------------------------------------------------------------------------------"  
echo "Check if path exists for group --> " $groupName " ?"

## Search and replace operation for S3 Storage on the group json file

if [[ "$oType" = "Linux" ]]; then
formatPath=$(echo $path | sed 's|\/|\\/|gI');
fi
if [[ "$oType" = "Windows" ]]; then
formatPath=$(cat wpath.txt | sed 's/\\/\\\\/gI');
fi  


if grep -qi -E "$formatPath($|\")" $groupName.json; then
echo "Input path found for group \:  " $groupName

data=$(cat $groupName.json | sed "s|realPath\"\:\"$formatPath\"|name\"\:\"$s3name\"|gI")

getUpdateGroupResponse=$(curl -s -k -b "$sid" -o /dev/null -w "%{http_code}" -H "x-js-at: $csrftoken" -H "X-Requested-With: XMLHttpRequest" -H "accept: application/json" -H "Content-type: application/json" -X PUT -d "$data" $proto://$jscapehost:$jscapemanagmentport/rest/management/groups/$domain/$groupName)

if [[ "$getUpdateGroupResponse" -eq 200 ]]; then  
echo "Updated the record for group --> " $groupName
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $groupName.json
fi
if [[ "$getUpdateGroupResponse" -eq 400 ]]; then  
echo "Update failed for the group --> " $groupName 
echo "Response code : 400 -- Bad Parameters"
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $groupName.json
fi
if [[ "$getUpdateGroupResponse" -eq 500 ]]; then  
echo "Update failed for the group --> " $groupName 
echo "Response code : 500 -- Internal server error"
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $groupName.json
fi
else
echo "Input path does not exist for group --> " $groupName " and nothing found to replace .."
echo "----------------------------------------------------------------------------------------------"
## Remove json after processing
rm $groupName.json   
fi 
fi 
done 
echo -e '\n'; 
echo "##################################################################"; 
echo "Processing the Groups module for " $domain " -- Completed"
echo "##################################################################"; 
rm groups.txt
fi

## failed creation check
if [[ "$getGroupsResponse" -eq 404 ]]; then 
echo -e '\n'; 
echo "Response Code : 404 -- Get groups list call failed, Recheck the parameters.."  
rm groups.txt
fi


## Groups -- End 
fi
else
echo -e '\n';   
echo "Login failed. Re-check REST username and password";  
fi
fi

## delete processing files
if [ -f wpath.txt ]; then
rm wpath.txt
fi    

### logout
curl -s -k -b "$sid" -H "x-js-at: $csrftoken" -X POST $proto://$jscapehost:$jscapemanagmentport/rest/management/logout

### delete cookie file
rm $cookie_file