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

# You need to provide these:
# CLIENT_ID=
# CLIENT_SECRET=
# ORG_ID=
# Check shared secrets
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="$PWD/authorization-post.log"

MESSAGE=$(cat -)
ADDR="$1"
NAME=$(echo "$ADDR" | jq -r .full_name)
STREET=$(echo "$ADDR" | jq -r .street)
CITY=$(echo "$ADDR" | jq -r .city)
POSTCODE=$(echo "$ADDR" | jq -r .postcode)
COUNTRY=$(echo "$ADDR" | jq -r .country)

MYDIR=$(mktemp -d /tmp/authorization-post-XXXXXX)
cd "$MYDIR"
cat - | sed -e "s/%NAME%/$NAME/g" \
	    -e "s/%STREET%/$STREET/g" \
	    -e "s/%POSTCODE%/$POSTCODE/g" \
	    -e "s/%CITY%/$CITY/g" \
	    -e "s/%COUNTRY%/$COUNTRY/g" > input.tex <<EOF
\NeedsTeXFormat{LaTeX2e}
\documentclass[fontsize=11pt,a4paper]{scrlttr2}
\makeatletter
\KOMAoptions{foldmarks=off}
\makeatother
\setkomavar{subject}{Anastasis Recovery}
\address{Anastasis SARL \\\\ 7 rue de Mondorf \\\\ 5431 Erpeldange}
\setkomavar{signature}{Anastasis SARL}
\date{\today}
\begin{document}
\begin{letter}{\ \ %NAME% \\\\ \ \ %STREET% \\\\ \ \ %POSTCODE% %CITY% \\\\ \ \ %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=$CLIENT_ID" \
	    --data-urlencode "client_secret=$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)

curl -s \
     -X PUT \
     -T input.pdf \
     "$UPLOAD_URL"

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/${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)
cat "$MYDIR/final-reply.txt" >> "$LOGS"
case "$STATUS" in
    201)
        ;;
    *)
        echo "Failed to add letter: $STATUS" >> "$LOGS"
	echo "$REPLY"
        exit 1;
        ;;
esac

rm -r "$MYDIR"
exit 0
