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

# You need to provide these (set in 'pingen-secrets' file).
# CLIENT_ID=
# CLIENT_SECRET=
# ORG_ID=
# . pingen-secrets

ENDPOINT="https://api.v2.pingen.com"
LOGS="$PWD/authorization-post.log"

MESSAGE=$(cat -)
DATE=$(date +%F)
ADDR="$1"
NAME=$(echo "$ADDR" | jq -r .full_name)
STREET=$(echo "$ADDR" | jq -r .street)

LNUMBER=$(echo $STREET | awk '{print $NF}')
FNUMBER=$(echo $STREET | awk '{print $1}')
case "$LNUMBER"
in
    ''|*[!0-9]*)
	case "$FNUMBER"
	in
	    ''|*[!0-9]*)
		NUMBER=0
		;;
	    *)
		NUMBER="$FNUMBER"
		;;
	esac
	;;
    *)
	NUMBER="$LNUMBER"
	;;
esac


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" \
	    -e "s/%MESSAGE%/$MESSAGE/g" > input.tex <<EOF
\NeedsTeXFormat{LaTeX2e}
\documentclass[fontsize=11pt,a4paper]{scrlttr2}
\makeatletter
\KOMAoptions{foldmarks=off}
%\@setplength{toaddrvpos}{30mm}
%\@setplength{toaddrhpos}{130mm}
%\@setplength{sigbeforevskip}{10mm}
\makeatother
\setkomavar{subject}{Anastasis Recovery}
%\setkomavar{fromname}{Anastasis SARL}
\setkomavar{signature}{Anastasis SARL}
\date{\today}
%\address{Anastasis SARL \\\\ 7 rue de Mondorf \\\\ 5431 Erpeldange}
%\signature{Anastasis SARL}
\begin{document}
\begin{letter}{\ \ %NAME% \\\\ \ \ %STREET% \\\\ \ \ %POSTCODE% %CITY% \\\\ \ \ %COUNTRY% }
\opening{To whom it may concern,}
%MESSAGE%
\closing{Best regards}
\end{letter}
\end{document}
EOF
pdflatex input.tex > /dev/null 2> /dev/null

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"


RECIPIENT="$(jq -n '
    {
        name: $NAME,
        street: $STREET,
 	number: $NUMBER,
        city: $CITY,
        zip: $POSTCODE,
        country: $COUNTRY,
    }' \
    --arg NAME "$NAME" \
    --arg STREET "$STREET" \
    --arg NUMBER "$NUMBER" \
    --arg CITY "$CITY" \
    --arg POSTCODE "$POSTCODE" \
    --arg COUNTRY "$COUNTRY" \
  )"

SENDER="$(jq -n '
    {
        name: "Anastasis SARL",
        street: "Rue de Mondorf",
 	number: "7",
	zip: "5421",
 	city: "Erpeldange",
	country: "LU"
    }'
  )"

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"
        } }
    }' \
    --argjson RECIPIENT "$RECIPIENT" \
    --argjson SENDER "$SENDER" \
    --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
LETTER_ID=$(cat $MYDIR/final-reply.txt | jq -r .data.id)
REPLY="$MYDIR/delete-reply.txt"
STATUS=409
sleep 1;
while test "$STATUS" = 409;
do
  STATUS=$(curl -s --request DELETE \
          --url "$ENDPOINT/organisations/$ORG_ID/letters/$LETTER_ID" \
          --header "Authorization: Bearer $ACCESS_TOKEN" \
          -o "$REPLY" \
          -w "%{http_code}" -s)
  case "$STATUS" in
    204)
	cat "$REPLY" >> "$LOGS"
        ;;
    409)
	# Happens, likely still in processing...
	;;
    *)
        echo "Failed to delete letter: $STATUS" >> "$LOGS"
        ;;
  esac
done

rm -r "$MYDIR"

exit 0
