#! /bin/bash
#
# Requires jq - see https://stedolan.github.io/jq/
#
# Assumes that the following env vars are set:
#
# CLIENT_ID - the client ID for your OAuth 2 app
# JWT_KEY_FILE - path to the private key for creating a JWT
# HUB_USERNAME - authentication username
# JWT login
sfdx force:auth:jwt:grant --clientid ${CLIENT_ID} \
--jwtkeyfile ${JWT_KEY_FILE} --username ${HUB_USERNAME} \
--setdefaultdevhubusername > /dev/null
# Create an org
created="$(sfdx force:org:create -s -f scratch-def.json --json)"
orgId="$(echo ${created} | jq -r .result.orgId)"
username="$(echo ${created} | jq -r .result.username)"
# Emit username
echo -n ${username}
# Generate user password
password="$(sfdx force:user:password:generate -u ${username} --json | jq -r .result.password)"
# Get accessToken, instanceUrl etc
org="$(sfdx force:org:display -u ${username} --json)"
accessToken="$(echo ${org} | jq -r .result.accessToken)"
instanceUrl="$(echo ${org} | jq -r .result.instanceUrl)"
# Get my IP address
myip="$(curl -s http://ipinfo.io/ip)"
# Wait until new instance resolves
until host ${instanceUrl} > /dev/null
do
sleep 10
done
# Set IP range
opened="$(curl -s ${instanceUrl}/services/Soap/m/39.0/${orgId} \
-H "Content-Type: text/xml; charset=UTF-8" \
-H "SOAPAction: updateMetadata" \
-d '
'${accessToken}'
'${myip}'
'${myip}'
')"
# Password might have characters that need to be escaped for XML!
esc_password="$(echo ${password} | sed 's/&/\&/g; s/\</g; s/>/\>/g; s/"/\"/g; s/'"'"'/\'/g')"
# Test login with username and password
login="$(curl -s https://test.salesforce.com/services/Soap/u/39.0 \
-H "Content-Type: text/xml; charset=UTF-8" \
-H "SOAPAction: login" \
-d '
'${username}'
'${esc_password}'
')"
if [[ $(echo ${login} | xpath '/soapenv:Envelope/soapenv:Body/loginResponse' 2> /dev/null) ]]; then
# All is good
exit 0
fi
# No loginResponse!
exit 1