#!/usr/bin/env bash
# box.sh: list a template's inputs, measure it and export it as a PDF with the PiQ SaaS API.
# bash, curl and jq.
set -euo pipefail

: "${PIQ_API_KEY:?Set PIQ_API_KEY to your API key.}"
base="${PIQ_URL:-https://saas.parametriq.co.uk}"
base="${base%/}"
storage="${PIQ_STORAGE:-}" # optional: a registered storage's name

TEMPLATE='L=400,"Length"
W=300,"Width"
P1=[L,0]
P2=[L,W]
P3=[0,W]
POLYLINE @1,[P0,P1,P2,P3],TRUE,0'
# the template itself, or (optional) where it is kept in your storage
if [ -n "$storage" ]; then
  template=$(jq -n --arg s "$storage" '{source: {storage: $s, key: "templates/box.piq"}}')
else
  template=$(jq -n --arg t "$TEMPLATE" '{template: $t}')
fi
request=$(jq '. + {values: {L: 500, W: 250}}' <<<"$template")
trap 'rm -f inputs.json measure.json saved.json headers.txt' EXIT

# post PATH BODY OUTPUT: posts the JSON body, the response to the file OUTPUT, its headers to headers.txt
post() {
  local status
  status=$(curl -sS -o "$3" -D headers.txt -w '%{http_code}' -X POST "$base$1" \
    -H "X-API-KEY: $PIQ_API_KEY" -H 'Content-Type: application/json' --data-binary "$2")
  if [ "$status" -ge 300 ]; then
    echo "Error $status" >&2
    if [ -s "$3" ]; then # a 401 has no body
      jq -r '.title // empty, .detail // empty,
        (.errors // {} | to_entries[] | "  \(.key): \(.value | join(" "))")' "$3" >&2 || cat "$3" >&2
    fi
    rm -f "$3"
    exit 1
  fi
}

# 1. The template's labelled variables
post /inputs "$template" inputs.json
jq -r '.inputs[] | "\(.name): \(.label) (\(.kind), \(.value))"' inputs.json

# 2. The drawing measured, with the values given
post /measure "$request" measure.json
jq -r '"Size: \(.width) x \(.height), cut length: \(.layers | map(select(.layer == "Cut").length) | add // 0)"' measure.json

# 3. The drawing as a PDF
post /export/pdf "$request" box.pdf
warnings=$(grep -i '^x-piq-warnings:' headers.txt | cut -d' ' -f2 | tr -d '\r')
echo "Saved box.pdf ($warnings warnings)"

# 4. Optional: the PDF saved to your storage instead of downloaded
if [ -n "$storage" ]; then
  body=$(jq --arg s "$storage" '. + {destination: {storage: $s, key: "drawings/box.pdf"}, overwrite: true}' <<<"$request")
  post /save/pdf "$body" saved.json
  jq -r '"Saved \(.key) to \(.storage) (\(.size) bytes)"' saved.json
fi
