#!/bin/bash
# This file is in the public domain.
#
# Challenger's /info returns the 'id' as a Number, but the
# exchange oauth2 plugin expects it as a String.
# Additionally, we need to check that we got the expected
# "postal" address type (and otherwise exit with failure),
# and finally move the .address values to
# the "ADDRESS_*" fields.
#
# Uses JQ to convert!
exec jq 'if .address_type!="postal" and .address_type !="postal-ch" then halt_error(4) else (. | .id?) |= (. | tostring) | .FORM_ID="challenger-postal" | .FORM_VERSION=0 | .CONTACT_NAME=.address.CONTACT_NAME | .ADDRESS_LINES=.address.ADDRESS_LINES | if .address_type=="postal" then .ADDRESS_COUNTRY=.address.ADDRESS_COUNTRY else .ADDRESS_COUNTRY="CH" end | del(.address) | del(.address_type) end'

# Example input:
# {
#   "id": 1,
#   "address": {
#     "CONTACT_NAME": "Richard Stallman",
#     "ADDRESS_LINES": "Bundesgasse 1\n1234 Bern"
#   },
#   "address_type": "postal-ch",
#   "expires": {
#     "t_s": 1775590216
#   }
# }
#
# Example output:
#
# {
#   "id": "1",
#   "expires": {
#     "t_s": 1775590216
#   }
#   "CONTACT_NAME": "Richard Stallman"
#   "ADDRESS_LIENS": "Bundesgasse 1\n1234 Bern"
#   "ADDRESS_COUNTRY": "CH"
# }
#
