#!/bin/bash

#
# The API function will initiate a REST API call to the XtremIO XMS with
# error checking.
#
# Usage :
#    API username password req_type URL req_body
#
#      username - The username to use to authenticate to the XMS (eg, admin)
#      password - The password to use to authenticate to the XMS
#      req_type - One of GET, POST, PUT or DELETE
#      URL      - The full URL to the resources
#      req_body - For POST/PUT, the JSON-formatted body of the request
#
# The function returns 0 if the request is successful, and the JSON response
# from the array (if any) is send to stdout, otherwise it returns non-zero.
#
API() {

        local TMPFILE=`mktemp`
        local BODY=""

        if [ $# -eq 5 ]; then
                BODY="-d ${5}"
        elif [ $# -ne 4 ]; then
                echo Invalid number of arguments past to API
                return 99
        fi

        local RESP=$(curl -s --output $TMPFILE --write-out "%{http_code}" -X ${3} ${BODY} -u ${1}:${2} -k -s ${4})

        if [ $? -ne 0 ]; then
                RESP=$?
        elif [ $RESP -ge 200 ] && [ $RESP -le 299 ];  then
                RESP=0
        else
                RESP=1
        fi

        cat $TMPFILE
        rm $TMPFILE

        return $RESP
}

Response=$(API admin Xtrem10 POST https://xms.example.com/api/json/v2/types/snapshots '{"from-consistency-group-id":"CG1","to-snapshot-set-id":"SS1","no-backup":"true"}')

if [ $? -eq 0 ]; then
        echo SUCCESS.  Response was :
        echo $Response
else
        echo ERROR.  Error was :
        echo $Response
fi

