#!/bin/bash

USAGE="$(cat <<EOF
usage: $0 PAYMENT_INTEGRATOR_ACCOUNT_ID INTEGRATOR_PRIVATE_KEY_EMAIL GOOGLE_PUBLIC_KEY_EMAIL

A script to call the Google-hosted echo API and print the results.

  PAYMENT_INTEGRATOR_ACCOUNT_ID  Google-assigned identifier string that
                                 uniquely identifies the integrator's account
                                 with Google.

  INTEGRATOR_PRIVATE_KEY_EMAIL   The email address that identifies the
                                 integrator's private key in gpg. Can be found
                                 using "gpg --list-secret-keys".

  GOOGLE_PUBLIC_KEY_EMAIL        The email address that identifies Google's
                                 public key in gpg. Can be found using
                                 "gpg --list-keys".

This script has several prerequisites:
 1) curl must be installed
 2) gpg must be installed
 3) both the local (integrator) private key and remote (Google) public key must
    be imported into the gpg toolchain. This can be done using 
    "gpg --import FILENAME"
EOF
)"

if [[ -z "$3" ]]
then
  echo "${USAGE}"
  exit
fi

PAYMENT_INTEGRATOR_ACCOUNT_ID="$1"
INTEGRATOR_PRIVATE_KEY_EMAIL="$2"
GOOGLE_PUBLIC_KEY_EMAIL="$3"

REQUEST_BODY="$(cat <<EOF
{
  "requestHeader": {
    "protocolVersion": {
      "major": 1,
      "minor": 0,
      "revision": 0
    },
    "requestId": "gsp_sandbox_echo_sh_$(date +'%s')_$RANDOM",
    "requestTimestamp": "$(date +'%s')000"
  },
  "clientMessage": "v1.echo client message"
}
EOF
)"

echo
echo -----REQUEST_BODY----
echo "${REQUEST_BODY?}"
echo

echo Encrypting REQUEST_BODY...

ENCRYPTED_REQUEST_BODY="$( \
  echo "${REQUEST_BODY?}" \
  | gpg --encrypt --sign --always-trust \
    --recipient "${GOOGLE_PUBLIC_KEY_EMAIL?}" \
    --local-user "${INTEGRATOR_PRIVATE_KEY_EMAIL?}"  \
  | base64 -w 0 \
  | sed 's/\+/-/g' \
  | sed 's#/#_#g' \
  )"

echo
echo -----ENCRYPTED_REQUEST_BODY----
echo "${ENCRYPTED_REQUEST_BODY?}"
echo

echo Calling echo endpoint with ENCRYPTED_REQUEST_BODY...
ENCRYPTED_RESPONSE_BODY="$(
  echo "${ENCRYPTED_REQUEST_BODY?}" \
  | curl -X POST -d @- \
  -H "Content-Type: application/octet-stream; charset=utf-8" \
  "https://billpaynotification.sandbox.googleapis.com/secure-serving/gsp/v1/echo/${PAYMENT_INTEGRATOR_ACCOUNT_ID?}" \
  )"

echo
echo -----ENCRYPTED_RESPONSE_BODY----
echo "${ENCRYPTED_RESPONSE_BODY?}"
echo

echo Decrypting ENCRYPTED_RESPONSE_BODY...
RESPONSE_BODY="$(\
  echo "${ENCRYPTED_RESPONSE_BODY?}" \
  | sed 's/-/+/g' \
  | sed 's#_#/#g' \
  | base64 --decode \
  | gpg --decrypt --always-trust \
    --recipient "${INTEGRATOR_PRIVATE_KEY_EMAIL?}" \
  )"

echo
echo -----RESPONSE_BODY----
echo "${RESPONSE_BODY?}"
echo
