#!/bin/bash

# A sample script for calls to the CLI. This one creates a Jet Stream container.
#
# VERY IMPORTANT: In order for this to work, you need to go through the steps here:
# https://docs.delphix.com/display/DOCS43/CLI+Cookbook%3A+Configuring+Key-Based+SSH+Authentication+for+Automation
# After this you will not need to use a username and password to log into the delphix engine. If you do not
# setup the SSH authentication you will have to manually enter the password.
#


##### Constants

# Describes a Delphix software revision.
VERSION="1.11.10"


##### Default Values. These can be overwriten with optional arguments.
engine="name-of-engine.dlpxdc.co"
username="admin"



##examples##
# Create container from latest point in time
#./createContainer.sh -n "testsource" testcont ORACLE_DB_CONTAINER-269 JS_DATA_TEMPLATE-13
# Create container from specific bookmark
#./createContainer.sh -n "testsource" -b JS_BOOKMARK-77 testcont ORACLE_DB_CONTAINER-269 JS_DATA_TEMPLATE-13
# Create container from specific point in time
#./createContainer.sh -n "testsource" -t "2016-08-08T10:00:00.000Z" -B JS_BRANCH-50 testcont ORACLE_DB_CONTAINER-269 JS_DATA_TEMPLATE-13

#NOTE: this script will add one container and assign one owner for the container.


##### Functions

# Help Menu
function usage {
	echo "Usage: createContainer.sh [[-h] | options...] <containername> <vdb> <template>"
	echo "Create a Jet Stream Container."
	echo ""
	echo "Positional arguments"
	echo "  <name>"
	echo "  <container> format JS_DATA_CONTAINER-<n>"
	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				  Server user. Password needs to manually provide at run time, otherwise revert to default"
    	echo "  -n                SourceName need to display for container.(Mandatory)"
	echo "  -b                Bookmark name from which need to create container. If no bookmark is included, the branch will be created at the latest point in time. Type: string. Format JS_BOOKMARK-<n> (Optional)"
	echo "  -B                Branch reference from which we need to pick up time from where the container should be created. Type: string. Format JS_BRANCH-<n>"
	echo "  -t                The time at which the branch should be created. This must be accompanied with branch name from which need to pick up time. Type: date, must be in ISO 8601 extended format [yyyy]-[MM]-[dd]T[HH]:[mm]:[ss].[SSS]Z"
    echo "  -N                Optional container notes, if need to add any. Type: String"
    echo "  -o                Optional owner, to whom we need to assign this container. Type: String. Format USER-<n>"
}

# Create Our Session, including establishing the API version.
function create_session
{
	echo "creating session..."
	SSH_CMD="ssh ${username}@${engine}"
	${SSH_CMD}  "version $VERSION"
	check_result
}

# 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"
		echo $result	
	    exit 1
	fi
}



function create_container
{  
	# If there is not timeInput and no bookmark name, we need to use JSTimelinePointLatestTimeInput.
	if [[ -z $inputTime  &&  -z $bookmark ]]
	then
		pointParams="set timelinePointParameters.type=JSTimelinePointLatestTimeInput;"
		pointParams="$pointParams set timelinePointParameters.sourceDataLayout=$template;"

   # If there is a timeInput, no bookmark name and a branch name, we need to use Input Time.
	elif [[ -n $inputTime  && -z $bookmark && -n $branch ]]
	 then
		pointParams="set timelinePointParameters.type=JSTimelinePointTimeInput;"
		pointParams="$pointParams set timelinePointParameters.time=\"${inputTime}\";"
		pointParams="$pointParams set timelinePointParameters.branch=$branch;"
# If there is a bookmark name and no time input, we need to use bookmark
	elif [[ -z $inputTime  &&  -n $bookmark ]]
	 then
		pointParams="set timelinePointParameters.type=JSTimelinePointBookmarkInput;"
		pointParams="$pointParams set timelinePointParameters.bookmark=\"${bookmark}\";"
	else
		usage
		exit 1
	fi
	
	# These are the required parameters.

	paramString="selfservice container create;set name=\"${containerName}\";"
	paramString="$paramString set template=\"${template}\";"

    if [[ -n $containerNotes ]]
    then
       paramString="$paramString set notes=\"${containerNotes}\";"
	fi

	if [[ -n $owners ]]
	then
      paramString="$paramString set owner=\"${owners}\";"
	fi
	paramString="$paramString $pointParams;"
	paramString="$paramString edit dataSources; add; set container=$VDB;"
	paramString="$paramString edit source; set type=JSDataSource; set priority=1;set name=\"${sourceName}\";"
    
    if [[ -n $sourcedesc ]]
    then
       paramString="$paramString set description=\"${sourcedesc}\";"  
    fi

    paramString="$paramString commit;"
	#echo $paramString
	echo "Creating Container..."
	result=$(${SSH_CMD}  $paramString)
	check_result

	echo "Verifying job status..."
	# Get everything in the result that comes after job.
    	temp=${result#*job}
  	# Get rid of everything after    
	resultArray=($temp)
	jobRef=($resultArray)
    	jobString="job;select $jobRef;ls"
    	result=$(${SSH_CMD} $jobString)
	check_result
	# Get everything in the result that comes after job.
	temp=${result#*jobState:}
	# Get rid of everything after
	resultArray=($temp)
	jobState=($resultArray)
    	if [ $jobState = "COMPLETED" ]
	then
		echo "Successfully created Container $containerName"
	else
		echo "Unable to create Container"
		echo $result
	fi
}	

##### Main

while getopts "u:d:b:t:B:D:n:N:o:h" flag; do
	case "$flag" in
    	u )             username=${OPTARG%:*}
						;;
		d )             engine=$OPTARG
						;;
		b )             bookmark=$OPTARG
						;;
		t )             inputTime=$OPTARG
						;;
        D )             sourcedesc=$OPTARG
                        ;; 
        n )             sourceName=$OPTARG
                        ;;
	B )             branch=$OPTARG
			;;	
        N )             containerNotes=$OPTARG
                        ;;                 
        o )             owners=$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 3 positional arguments
if [ $# != 3 ]
then
	usage
	exit 1
fi

# Get the three positional arguments
containerName=$1
shift
VDB=$1
shift
template=$1

create_session
create_container

