#!/bin/bash

# A sample script for calls to the API. This one creates a Jet Stream user.

##### Constants

# Describes a Delphix software revision.
# Please change version are per your Delphix Engine CLI, if different
VERSION="1.11.9"


##### Default Values. These can be overwriten with optional arguments.
engine="10.43.90.86"
username="admin"
password="delphix"

##examples##
# Create user with NATIVE authentication
#./createJSUser.sh -P <password> NATIVE <username>
# Create user with LDAP authentication
#./createJSUser.sh -r <principal> <LDAP username>

##### Functions

# Help Menu
function usage {
	echo "Usage: createJSUser.sh [[-h] | options...] <auth> <newjsuser>"
	echo "Create a Jet Stream Only user."
	echo ""
	echo "Positional arguments"
	echo "  <auth>"
	echo "  <newjsuser>"
	echo ""
	echo "Optional Arguments:"
	echo "  -h                Show this message and exit"
	echo "  -d                Delphix engine IP address or host name, otherwise revert to default"
	echo "  -u USER:PASSWORD  Server user and password, otherwise revert to default"
	echo "  -P               password for NATIVE authentication"
    echo "  -f                firstName of user"
    echo "  -l                lastName of user"
    echo "  -e                emailAddress of user" 
    echo "  -o                homePhoneNumber of user" 
    echo "  -m                mobilePhoneNumber of user" 
    echo "  -w                workPhoneNumber of user" 
    echo "  -r               principal for LDAP authentication"
}

# Create Our Session, including establishing the API version.
function create_session
{
	# Pulling the version into parts. The {} are necessary for string manipulation.
	# Strip out longest match following "."  This leaves only the major version.
	major=${VERSION%%.*}
	# Strip out the shortest match preceding "." This leaves minor.micro.
	minorMicro=${VERSION#*.}
	# Strip out the shortest match followint "." This leaves the minor version.
	minor=${minorMicro%.*}
	# Strip out the longest match preceding "." This leaves the micro version.
	micro=${VERSION##*.}

	# Quick note about the <<-. If the redirection operator << is followed by a - (dash), all leading TAB from the document data will be 
	# ignored. This is useful to have optical nice code also when using here-documents. Otherwise you must have the EOF be on a line by itself, 
	# no parens, no tabs or anything.

	echo "creating session..."
	result=$(curl -s -S -X POST -k --data @- http://${engine}/resources/json/delphix/session \
		-c ~/cookies.txt -H "Content-Type: application/json" <<-EOF
	{
		"type": "APISession",
		"version": {
			"type": "APIVersion",
			"major": $major,
			"minor": $minor,
			"micro": $micro
		}
	}
	EOF)

	check_result
}

# Authenticate the DE for the provided user.
function authenticate_de
{
	echo "authenticating delphix engine..."
	result=$(curl -s -S -X POST -k --data @- http://${engine}/resources/json/delphix/login \
		-b ~/cookies.txt -c ~/cookies.txt -H "Content-Type: application/json" <<-EOF
	{
		"type": "LoginRequest",
		"username": "${username}",
		"password": "${password}"
	}
	EOF)	

	check_result
}

function create_user
{
	# Check on authorization type
	
	if [[ $authtype = "NATIVE"  &&  -n $userpwd ]]
	then  
		pointParams="\"authenticationType\":\"$authtype\",
		             \"credential\":{
			         \"type\":\"PasswordCredential\",
			         \"password\":\"$userpwd\"}"

    elif [[ $authtype = "LDAP"  &&  -n $principal ]]
	then
		pointParams="\"authenticationType\":\"$authtype\",
			         \"principal\":\"$principal\""			            

	fi

	# These are the required parameters.
	paramString="
	        \"type\": \"User\",
	        \"name\": \"${newjsuser}\","	
      
	        
	# Fill in optional parameters if there are any.
	if [[ -n $firstname ]]
	then
		paramString="$paramString \"firstName\": \"$firstname\","     
	fi
	
	if [[ -n $lastname ]]
	then
		paramString="$paramString \"lastName\": \"$lastname\","     
	fi	 
	
	if [[ -n $emailaddress ]]
	then
		paramString="$paramString \"emailAddress\": \"$emailaddress\","     
	fi  
	
	if [[ -n $homephone ]]
	then
		paramString="$paramString \"homePhoneNumber\": \"$homephone\","     
	fi 
	
	if [[ -n $mobilephone ]]
	then
		paramString="$paramString \"mobilePhoneNumber\": \"$mobilephone\","     
	fi 
	
	if [[ -n $workphone ]]
	then
		paramString="$paramString \"workPhoneNumber\": \"$workphone\","     
	fi 
	        
	        
	paramString="$paramString 
	    ${pointParams}" 

	result=$(curl -s -X POST -k --data @- http://${engine}/resources/json/delphix/user \
	    -b ~/cookies.txt -H "Content-Type: application/json" <<-EOF
	{
	    $paramString
	}
	EOF)
	
	check_result
	
	# Extracting USER ID from result
    temp=${result#*\"result\":\"}
    userRef=${temp%%\"*}
	
	echo "New user $newjsuser successfully created"
	
	##### ROLE-3 is Jet Stream Role 
	
	result=$(curl -s -X POST -k --data @- http://${engine}/resources/json/delphix/authorization \
	   -b ~/cookies.txt -H "Content-Type: application/json" <<-EOF
	{
    "type": "Authorization",
    "role": "ROLE-3",
    "target": "$userRef",
    "user": "$userRef"
    }
	EOF)

	check_result
	
    echo "Assigned Jet Stream Role to user $newjsuser"

}

# Check the result of the curl. If there are problems, inform the user then exit.
function check_result
{
	exitStatus=$?
	if [ $exitStatus -ne 0 ]
	then
	    echo "command failed with exit status $exitStatus"
	    exit 1
	elif [[ $result != *"OKResult"* ]]
	then
		echo ""
		echo $result
		exit 1
	fi
}

##### Main

while getopts "u:d:P:r:f:l:e:o:m:w:h" flag; do
	case "$flag" in
    	u )             username=${OPTARG%:*}
						password=${OPTARG##*:}
						;;
		d )             engine=$OPTARG
						;;
	    P )             userpwd=$OPTARG
						;;
	    r )             principal=$OPTARG
						;;								
	    f )             firstname=$OPTARG
						;;
	    l )             lastname=$OPTARG
						;;
        e )             emailaddress=$OPTARG
                        ;;
        o )             homephone=$OPTARG
						;;
	    m )             mobilephone=$OPTARG
						;;
        w )             workphone=$OPTARG
                        ;;                 
	    h )             usage
						exit
						;;
		* )             usage
						exit 1
  					
	esac

done


# Shift the parameters so we only have the positional arguments left
shift $((OPTIND-1))

# Check that there are 2 positional arguments
if [ $# != 2 ]
then
  echo "usage1"
	usage
	exit 1
fi

# Get the two positional arguments
authtype=$1
shift
newjsuser=$1

create_session
authenticate_de
create_user


