#!/bin/bash
# This file is in the public domain.
set -eux

# You need to provide these (set in environment).
# PINGEN_CLIENT_ID=
# PINGEN_CLIENT_SECRET=
# PINGEN_ORG_ID=
if [ -x "$PINGEN_CLIENT_ID" ]
then
    echo "PINGEN_CLIENT_ID not sent in environment"
    exit 1
fi
if [ -x "$PINGEN_CLIENT_SECRET" ]
then
    echo "PINGEN_CLIENT_SECRET not sent in environment"
    exit 1
fi
if [ -x "$PINGEN_ORG_ID" ]
then
    echo "PINGEN_ORG_ID not sent in environment"
    exit 1
fi

ENDPOINT="https://api.pingen.com"
LOGS="$HOME/authorization-post.log"
ERRORS="$HOME/authorization-post.err"

MESSAGE=$(cat -)
ADDR="$1"
# We'll use "tr" to filter out anything that could be a problem in LaTeX.
# Name of business or individual, possibly with "Attn. $INDIVIDUAL_NAME"
CONTACT_NAME=$(echo "$ADDR" | jq -r .CONTACT_NAME | tr '|`~!"<>[]%_^#$&@\\{}' . )
# Multi-line address
ADDRESS_LINES=$(echo "$ADDR" | jq -r .ADDRESS_LINES)
# This will just be the 2-letter country code
ADDRESS_COUNTRY=$(echo "$ADDR" | jq -r .ADDRESS_COUNTRY | tr '|`~!"<>[]%_^#$&@\\{}' . )

case "$ADDRESS_COUNTRY"
in
	AF)
		COUNTRY='Afghanistan'
		;;
	AX)
		COUNTRY='Åland Islands'
		;;
	AL)
		COUNTRY='Albania'
		;;
	DZ)
		COUNTRY='Algeria'
		;;
	AS)
		COUNTRY='American Samoa'
		;;
	AD)
		COUNTRY='Andorra'
		;;
	AO)
		COUNTRY='Angola'
		;;
	AI)
		COUNTRY='Anguilla'
		;;
	AQ)
		COUNTRY='Antarctica'
		;;
	AG)
		COUNTRY='Antigua \\\& Barbuda'
		;;
	AR)
		COUNTRY='Argentina'
		;;
	AM)
		COUNTRY='Armenia'
		;;
	AW)
		COUNTRY='Aruba'
		;;
	AU)
		COUNTRY='Australia'
		;;
	AT)
		COUNTRY='Austria'
		;;
	AZ)
		COUNTRY='Azerbaijan'
		;;
	BS)
		COUNTRY='Bahamas'
		;;
	BH)
		COUNTRY='Bahrain'
		;;
	BD)
		COUNTRY='Bangladesh'
		;;
	BB)
		COUNTRY='Barbados'
		;;
	BY)
		COUNTRY='Belarus'
		;;
	BE)
		COUNTRY='Belgium'
		;;
	BZ)
		COUNTRY='Belize'
		;;
	BJ)
		COUNTRY='Benin'
		;;
	BM)
		COUNTRY='Bermuda'
		;;
	BT)
		COUNTRY='Bhutan'
		;;
	BO)
		COUNTRY='Bolivia'
		;;
	BA)
		COUNTRY='Bosnia \\\& Herzegovina'
		;;
	BW)
		COUNTRY='Botswana'
		;;
	BV)
		COUNTRY='Bouvet Island'
		;;
	BR)
		COUNTRY='Brazil'
		;;
	IO)
		COUNTRY='British Indian Ocean Territory'
		;;
	VG)
		COUNTRY='British Virgin Islands'
		;;
	BN)
		COUNTRY='Brunei'
		;;
	BG)
		COUNTRY='Bulgaria'
		;;
	BF)
		COUNTRY='Burkina Faso'
		;;
	BI)
		COUNTRY='Burundi'
		;;
	KH)
		COUNTRY='Cambodia'
		;;
	CM)
		COUNTRY='Cameroon'
		;;
	CA)
		COUNTRY='Canada'
		;;
	CV)
		COUNTRY='Cape Verde'
		;;
	BQ)
		COUNTRY='Caribbean Netherlands'
		;;
	KY)
		COUNTRY='Cayman Islands'
		;;
	CF)
		COUNTRY='Central African Republic'
		;;
	TD)
		COUNTRY='Chad'
		;;
	CL)
		COUNTRY='Chile'
		;;
	CN)
		COUNTRY='China'
		;;
	CX)
		COUNTRY='Christmas Island'
		;;
	CC)
		COUNTRY='Cocos'
		;;
	CO)
		COUNTRY='Colombia'
		;;
	KM)
		COUNTRY='Comoros'
		;;
	CG)
		COUNTRY='Congo - Brazzaville'
		;;
	CD)
		COUNTRY='Congo - Kinshasa'
		;;
	CK)
		COUNTRY='Cook Islands'
		;;
	CR)
		COUNTRY='Costa Rica'
		;;
	CI)
#shellcheck disable=SC1112
		COUNTRY='Côte d’Ivoire'
		;;
	HR)
		COUNTRY='Croatia'
		;;
	CU)
		COUNTRY='Cuba'
		;;
	CW)
		COUNTRY='Curaçao'
		;;
	CY)
		COUNTRY='Cyprus'
		;;
	CZ)
		COUNTRY='Czechia'
		;;
	DK)
		COUNTRY='Denmark'
		;;
	DJ)
		COUNTRY='Djibouti'
		;;
	DM)
		COUNTRY='Dominica'
		;;
	DO)
		COUNTRY='Dominican Republic'
		;;
	EC)
		COUNTRY='Ecuador'
		;;
	EG)
		COUNTRY='Egypt'
		;;
	SV)
		COUNTRY='El Salvador'
		;;
	GQ)
		COUNTRY='Equatorial Guinea'
		;;
	ER)
		COUNTRY='Eritrea'
		;;
	EE)
		COUNTRY='Estonia'
		;;
	SZ)
		COUNTRY='Eswatini'
		;;
	ET)
		COUNTRY='Ethiopia'
		;;
	FK)
		COUNTRY='Falkland Islands'
		;;
	FO)
		COUNTRY='Faroe Islands'
		;;
	FJ)
		COUNTRY='Fiji'
		;;
	FI)
		COUNTRY='Finland'
		;;
	FR)
		COUNTRY='France'
		;;
	GF)
		COUNTRY='French Guiana'
		;;
	PF)
		COUNTRY='French Polynesia'
		;;
	TF)
		COUNTRY='French Southern Territories'
		;;
	GA)
		COUNTRY='Gabon'
		;;
	GM)
		COUNTRY='Gambia'
		;;
	GE)
		COUNTRY='Georgia'
		;;
	DE)
		COUNTRY='Germany'
		;;
	GH)
		COUNTRY='Ghana'
		;;
	GI)
		COUNTRY='Gibraltar'
		;;
	GR)
		COUNTRY='Greece'
		;;
	GL)
		COUNTRY='Greenland'
		;;
	GD)
		COUNTRY='Grenada'
		;;
	GP)
		COUNTRY='Guadeloupe'
		;;
	GU)
		COUNTRY='Guam'
		;;
	GT)
		COUNTRY='Guatemala'
		;;
	GG)
		COUNTRY='Guernsey'
		;;
	GN)
		COUNTRY='Guinea'
		;;
	GW)
		COUNTRY='Guinea-Bissau'
		;;
	GY)
		COUNTRY='Guyana'
		;;
	HT)
		COUNTRY='Haiti'
		;;
	HM)
		COUNTRY='Heard \\\& McDonald Islands'
		;;
	HN)
		COUNTRY='Honduras'
		;;
	HK)
		COUNTRY='Hong Kong SAR China'
		;;
	HU)
		COUNTRY='Hungary'
		;;
	IS)
		COUNTRY='Iceland'
		;;
	IN)
		COUNTRY='India'
		;;
	ID)
		COUNTRY='Indonesia'
		;;
	IR)
		COUNTRY='Iran'
		;;
	IQ)
		COUNTRY='Iraq'
		;;
	IE)
		COUNTRY='Ireland'
		;;
	IM)
		COUNTRY='Isle of Man'
		;;
	IL)
		COUNTRY='Israel'
		;;
	IT)
		COUNTRY='Italy'
		;;
	JM)
		COUNTRY='Jamaica'
		;;
	JP)
		COUNTRY='Japan'
		;;
	JE)
		COUNTRY='Jersey'
		;;
	JO)
		COUNTRY='Jordan'
		;;
	KZ)
		COUNTRY='Kazakhstan'
		;;
	KE)
		COUNTRY='Kenya'
		;;
	KI)
		COUNTRY='Kiribati'
		;;
	KW)
		COUNTRY='Kuwait'
		;;
	KG)
		COUNTRY='Kyrgyzstan'
		;;
	LA)
		COUNTRY='Laos'
		;;
	LV)
		COUNTRY='Latvia'
		;;
	LB)
		COUNTRY='Lebanon'
		;;
	LS)
		COUNTRY='Lesotho'
		;;
	LR)
		COUNTRY='Liberia'
		;;
	LY)
		COUNTRY='Libya'
		;;
	LI)
		COUNTRY='Liechtenstein'
		;;
	LT)
		COUNTRY='Lithuania'
		;;
	LU)
		COUNTRY='Luxembourg'
		;;
	MO)
		COUNTRY='Macao SAR China'
		;;
	MG)
		COUNTRY='Madagascar'
		;;
	MW)
		COUNTRY='Malawi'
		;;
	MY)
		COUNTRY='Malaysia'
		;;
	MV)
		COUNTRY='Maldives'
		;;
	ML)
		COUNTRY='Mali'
		;;
	MT)
		COUNTRY='Malta'
		;;
	MH)
		COUNTRY='Marshall Islands'
		;;
	MQ)
		COUNTRY='Martinique'
		;;
	MR)
		COUNTRY='Mauritania'
		;;
	MU)
		COUNTRY='Mauritius'
		;;
	YT)
		COUNTRY='Mayotte'
		;;
	MX)
		COUNTRY='Mexico'
		;;
	FM)
		COUNTRY='Micronesia'
		;;
	MD)
		COUNTRY='Moldova'
		;;
	MC)
		COUNTRY='Monaco'
		;;
	MN)
		COUNTRY='Mongolia'
		;;
	ME)
		COUNTRY='Montenegro'
		;;
	MS)
		COUNTRY='Montserrat'
		;;
	MA)
		COUNTRY='Morocco'
		;;
	MZ)
		COUNTRY='Mozambique'
		;;
	MM)
		COUNTRY='Myanmar'
		;;
	NA)
		COUNTRY='Namibia'
		;;
	NR)
		COUNTRY='Nauru'
		;;
	NP)
		COUNTRY='Nepal'
		;;
	NL)
		COUNTRY='Netherlands'
		;;
	NC)
		COUNTRY='New Caledonia'
		;;
	NZ)
		COUNTRY='New Zealand'
		;;
	NI)
		COUNTRY='Nicaragua'
		;;
	NE)
		COUNTRY='Niger'
		;;
	NG)
		COUNTRY='Nigeria'
		;;
	NU)
		COUNTRY='Niue'
		;;
	NF)
		COUNTRY='Norfolk Island'
		;;
	KP)
		COUNTRY='North Korea'
		;;
	MK)
		COUNTRY='North Macedonia'
		;;
	MP)
		COUNTRY='Northern Mariana Islands'
		;;
	NO)
		COUNTRY='Norway'
		;;
	OM)
		COUNTRY='Oman'
		;;
	PK)
		COUNTRY='Pakistan'
		;;
	PW)
		COUNTRY='Palau'
		;;
	PS)
		COUNTRY='Palestinian Territories'
		;;
	PA)
		COUNTRY='Panama'
		;;
	PG)
		COUNTRY='Papua New Guinea'
		;;
	PY)
		COUNTRY='Paraguay'
		;;
	PE)
		COUNTRY='Peru'
		;;
	PH)
		COUNTRY='Philippines'
		;;
	PN)
		COUNTRY='Pitcairn Islands'
		;;
	PL)
		COUNTRY='Poland'
		;;
	PT)
		COUNTRY='Portugal'
		;;
	PR)
		COUNTRY='Puerto Rico'
		;;
	QA)
		COUNTRY='Qatar'
		;;
	RE)
		COUNTRY='Réunion'
		;;
	RO)
		COUNTRY='Romania'
		;;
	RU)
		COUNTRY='Russia'
		;;
	RW)
		COUNTRY='Rwanda'
		;;
	WS)
		COUNTRY='Samoa'
		;;
	SM)
		COUNTRY='San Marino'
		;;
	ST)
		COUNTRY='São Tomé \\\& Príncipe'
		;;
	SA)
		COUNTRY='Saudi Arabia'
		;;
	SN)
		COUNTRY='Senegal'
		;;
	RS)
		COUNTRY='Serbia'
		;;
	SC)
		COUNTRY='Seychelles'
		;;
	SL)
		COUNTRY='Sierra Leone'
		;;
	SG)
		COUNTRY='Singapore'
		;;
	SX)
		COUNTRY='Sint Maarten'
		;;
	SK)
		COUNTRY='Slovakia'
		;;
	SI)
		COUNTRY='Slovenia'
		;;
	SB)
		COUNTRY='Solomon Islands'
		;;
	SO)
		COUNTRY='Somalia'
		;;
	ZA)
		COUNTRY='South Africa'
		;;
	GS)
		COUNTRY='South Georgia \\\& South Sandwich Islands'
		;;
	KR)
		COUNTRY='South Korea'
		;;
	SS)
		COUNTRY='South Sudan'
		;;
	ES)
		COUNTRY='Spain'
		;;
	LK)
		COUNTRY='Sri Lanka'
		;;
	BL)
		COUNTRY='St. Barthélemy'
		;;
	SH)
		COUNTRY='St. Helena'
		;;
	KN)
		COUNTRY='St. Kitts \\\& Nevis'
		;;
	LC)
		COUNTRY='St. Lucia'
		;;
	MF)
		COUNTRY='St. Martin'
		;;
	PM)
		COUNTRY='St. Pierre \\\& Miquelon'
		;;
	VC)
		COUNTRY='St. Vincent \\\& Grenadines'
		;;
	SD)
		COUNTRY='Sudan'
		;;
	SR)
		COUNTRY='Suriname'
		;;
	SJ)
		COUNTRY='Svalbard \\\& Jan Mayen'
		;;
	SE)
		COUNTRY='Sweden'
		;;
	CH)
		COUNTRY='Switzerland'
		;;
	SY)
		COUNTRY='Syria'
		;;
	TW)
		COUNTRY='Taiwan'
		;;
	TJ)
		COUNTRY='Tajikistan'
		;;
	TZ)
		COUNTRY='Tanzania'
		;;
	TH)
		COUNTRY='Thailand'
		;;
	TL)
		COUNTRY='Timor-Leste'
		;;
	TG)
		COUNTRY='Togo'
		;;
	TK)
		COUNTRY='Tokelau'
		;;
	TO)
		COUNTRY='Tonga'
		;;
	TT)
		COUNTRY='Trinidad \\\& Tobago'
		;;
	TN)
		COUNTRY='Tunisia'
		;;
	TR)
		COUNTRY='Turkey'
		;;
	TM)
		COUNTRY='Turkmenistan'
		;;
	TC)
		COUNTRY='Turks \\\& Caicos Islands'
		;;
	TV)
		COUNTRY='Tuvalu'
		;;
	UM)
		COUNTRY='U.S. Outlying Islands'
		;;
	VI)
		COUNTRY='U.S. Virgin Islands'
		;;
	UG)
		COUNTRY='Uganda'
		;;
	UA)
		COUNTRY='Ukraine'
		;;
	AE)
		COUNTRY='United Arab Emirates'
		;;
	GB)
		COUNTRY='United Kingdom'
		;;
	US)
		COUNTRY='United States'
		;;
	UY)
		COUNTRY='Uruguay'
		;;
	UZ)
		COUNTRY='Uzbekistan'
		;;
	VU)
		COUNTRY='Vanuatu'
		;;
	VA)
		COUNTRY='Vatican City'
		;;
	VE)
		COUNTRY='Venezuela'
		;;
	VN)
		COUNTRY='Vietnam'
		;;
	WF)
		COUNTRY='Wallis \\\& Futuna'
		;;
	EH)
		COUNTRY='Western Sahara'
		;;
	YE)
		COUNTRY='Yemen'
		;;
	ZM)
		COUNTRY='Zambia'
		;;
	ZW)
		COUNTRY='Zimbabwe'
		;;
    *)
        echo "ERROR: Country code '${ADDRESS_COUNTRY}' not recognized" 1>&2
        COUNTRY="${ADDRESS_COUNTRY}"
        ;;
esac

# Convert new lines to " " for LaTeX. excluding trailing new-line
# at the end if present:
CONTACT_TEX=$(echo -n "${CONTACT_NAME%$'\n'}" | awk '{printf "%s ", $0}')
# Convert new lines to "\\" for LaTeX, and escape problematic characters,
# but leave "\\" intact.
ADDRESS_TEX=$(echo -n "${ADDRESS_LINES%$'\n'}" | awk '{printf "%s\\\\\\\\", $0}' | tr '|`~!"<>[]%_^#$&@{}' . | sed 's/\\\\/@@ESCAPED@@/g; s/\\./\./g; s/@@ESCAPED@@/\\\\/g')


MYDIR=$(mktemp -d /tmp/authorization-post-XXXXXX)
cd "$MYDIR"
sed -e "s|%NAME%|$CONTACT_TEX|g" \
	    -e "s|%ADDRESS_TEX%|$ADDRESS_TEX|g" \
	    -e "s/%COUNTRY%/$COUNTRY/g" > input.tex <<EOF
\NeedsTeXFormat{LaTeX2e}
\documentclass[fontsize=11pt,a4paper]{scrlttr2}
\makeatletter
\KOMAoptions{foldmarks=off}
\makeatother
\setplength{toaddrhpos}{3cm}
\setkomavar{subject}{Address validation}
\setkomavar{signature}{Taler Operations AG, c/o Berner Fachhochschule, H\"oheweg 80, 2502 Biel/Bienne}
\date{\today}
\begin{document}
\begin{letter}{%NAME%\\\\ %ADDRESS_TEX% %COUNTRY%}
\opening{To whom it may concern,}
EOF
echo "$MESSAGE" >> input.tex
cat - >> input.tex <<EOF
\closing{Best regards}
\end{letter}
\end{document}
EOF
pdflatex input.tex > "$MYDIR/pdflatex.out" 2> "$MYDIR/pdflatex.err"

REPLY=$(curl \
	    -s \
	    -X POST \
	    -H "Content-Type: application/x-www-form-urlencoded" \
	    --data-urlencode "grant_type=client_credentials" \
	    --data-urlencode "client_id=$PINGEN_CLIENT_ID" \
	    --data-urlencode "client_secret=$PINGEN_CLIENT_SECRET" \
	    --data-urlencode "scope=letter" \
	    https://identity.pingen.com/auth/access-tokens)

ACCESS_TOKEN=$(echo "$REPLY" | jq -r .access_token)

REPLY=$(curl -s \
    -X GET "$ENDPOINT/file-upload" \
    -H  "Authorization: Bearer $ACCESS_TOKEN")
ATTRS=$(echo "$REPLY" | jq .data.attributes)
UPLOAD_URL=$(echo "$ATTRS" | jq -r .url)
URL_SIG=$(echo "$ATTRS" | jq -r .url_signature)

STATUS=$(curl -s \
     -X PUT \
     -T input.pdf \
     "$UPLOAD_URL" \
     -o "$MYDIR/upload-status.txt" \
     -w "%{http_code}" -s)

case "$STATUS" in
    200)
        ;;
    201)
        ;;
    204)
        ;;
    *)
        echo "Failed to upload letter: $STATUS" >> "$ERRORS"
        cat "$MYDIR/upload-status.txt" >> "$ERRORS"
        exit 1;
        ;;
esac


REQUEST="$(jq -n '
    {   data: {
        type: "letters",
	attributes: {
	  file_original_name: "input.pdf",
	  file_url: $UPLOAD_URL,
	  file_url_signature: $URL_SIG,
	  address_position: "left",
	  delivery_product: "cheap",
	  print_mode: "duplex",
	  auto_send: true,
 	  print_spectrum: "grayscale"
        } }
    }' \
    --arg UPLOAD_URL "$UPLOAD_URL" \
    --arg URL_SIG "$URL_SIG" \
  )"

STATUS=$(curl -s \
     --request POST \
     --url "$ENDPOINT/organisations/${PINGEN_ORG_ID}/letters" \
     --header "Content-Type: application/vnd.api+json" \
     --header "Authorization: Bearer $ACCESS_TOKEN" \
     -d "$REQUEST" \
     -o "$MYDIR/final-reply.txt" \
     -w "%{http_code}" -s)
case "$STATUS" in
    201)
        cat "$MYDIR/final-reply.txt" >> "$LOGS"
        ;;
    *)
        echo "Failed to add letter: $STATUS" >> "$ERRORS"
        cat "$MYDIR/final-reply.txt" >> "$ERRORS"
        exit 1;
        ;;
esac

rm -r "$MYDIR"
exit 0
