#!/usr/bin/env bash
# Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
# someone enters the code in the app. Needs bash, curl and jq.
#
#   bash pair-device.sh
#
# PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
# PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
# PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
set -euo pipefail

# What the device shows, in the language of the location.
TEXT_CODE='Code am Tisch: %s %s  (gilt bis %s UTC)\n'
TEXT_LINK='QR-Code mit diesem Link: %s\n'
TEXT_ENTER='Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.'
TEXT_EXPIRED='Der Code ist abgelaufen. Ich hole einen neuen.'
TEXT_UNPAIRED='Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.'
TEXT_OFF='Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.'
TEXT_OFFLINE='Keine Verbindung (%s), neuer Versuch in %s s\n'
TEXT_NO_KEY='Kein Idempotency-Key: weder /proc/sys/kernel/random/uuid noch uuidgen noch od gefunden.'
TEXT_PAIRED='"Verbunden mit \(.data.table.name) (\(.data.location.name // "ohne Standort"))"'
TEXT_ERROR='Fehler %s %s: %s\n'

BASE_URL="${PACKEROO_BASE_URL:-https://api.qm.packeroo.com/api/v1}"
BASE_URL="${BASE_URL%/}"
TOKEN_FILE="${PACKEROO_TOKEN_FILE:-$HOME/.config/packeroo/device-token}"
POLL_SECONDS="${PACKEROO_POLL_SECONDS:-5}"
MAX_PAUSE_SECONDS=60 # After errors in a row the pause doubles, up to this many seconds.
USER_AGENT="Kickertisch-Beispiel/1.0" # Every request names the device: product and firmware.

BODY_FILE="$(mktemp)"
HEADER_FILE="$(mktemp)"
trap 'rm -f "$BODY_FILE" "$HEADER_FILE"' EXIT

# call METHOD PATH [TOKEN] [IDEMPOTENCY_KEY] [JSON]: prints the status, the body is in $BODY_FILE.
# Network errors are retried.
call() {
  local method="$1" path="$2" token="${3:-}" key="${4:-}" json="${5:-}"
  local args=(-sS -X "$method" -o "$BODY_FILE" -D "$HEADER_FILE" -w '%{http_code}' --max-time 30
    -H "User-Agent: $USER_AGENT" -H 'Accept: application/json' -H 'Accept-Language: de')
  # A write carries an Idempotency-Key; a retry of the same request sends the same key.
  [[ -n "$key" ]] && args+=(-H "Idempotency-Key: $key")
  [[ -n "$json" ]] && args+=(-H 'Content-Type: application/json' --data "$json")
  local status error failures=0
  # The token reaches curl on stdin (--config -), not on the command line, where ps would show it.
  until status="$(curl "${args[@]}" --config - "$BASE_URL$path" <<< "${token:+header = \"Authorization: Bearer $token\"}")"; do
    error=$?
    failures=$((failures + 1))
    pause_after_error "$failures" "curl $error"
  done
  echo "$status"
}

# Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
# error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
pause_after_error() {
  local seconds
  seconds="$(awk -v poll="$POLL_SECONDS" -v n="$1" -v max="$MAX_PAUSE_SECONDS" 'BEGIN { s = poll * 2 ^ (n - 1); print (s > max ? max : s) }')"
  printf "$TEXT_OFFLINE" "$2" "$seconds" >&2
  sleep "$seconds"
}

# Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date.
retry_after() {
  local value seconds
  value="$(grep -i '^retry-after:' "$HEADER_FILE" | cut -d: -f2- | tr -d '\r' | sed 's/^ *//' || true)"
  if [[ "$value" =~ ^[0-9]+$ ]]; then seconds="$value"
  elif [[ -n "$value" ]] && date -d "$value" +%s >/dev/null 2>&1; then seconds=$(( $(date -d "$value" +%s) - $(date +%s) ))
  else seconds=60
  fi
  (( seconds < 1 )) && seconds=1
  echo "$seconds"
}

problem() { jq -r '.code // empty' "$BODY_FILE" 2>/dev/null || true; }

fail() {
  printf "$TEXT_ERROR" "$1" "$(problem)" "$(jq -r '.detail // "unerwartete Antwort"' "$BODY_FILE" 2>/dev/null)" >&2
  exit 1
}

new_key() {
  if [[ -r /proc/sys/kernel/random/uuid ]]; then cat /proc/sys/kernel/random/uuid
  elif command -v uuidgen >/dev/null; then uuidgen | tr 'A-Z' 'a-z'
  elif command -v od >/dev/null; then od -An -N16 -tx1 /dev/urandom | tr -d ' \n' | sed -E 's/(.{8})(.{4}).(.{3}).(.{3})(.{12})/\1-\2-4\3-a\4-\5/'
  fi
}

# Keeps the token in a file only this user can read, written in one step.
save_token() {
  mkdir -p "$(dirname "$TOKEN_FILE")"
  chmod 700 "$(dirname "$TOKEN_FILE")" 2>/dev/null || true
  # A leftover from a crash may have other rights: remove it, then create the file anew
  # (with noclobber, > fails instead of writing into a file that is there).
  rm -f "$TOKEN_FILE.tmp"
  (umask 077 && set -o noclobber && printf '%s\n' "$1" > "$TOKEN_FILE.tmp")
  mv -f "$TOKEN_FILE.tmp" "$TOKEN_FILE"
}

show_code() {
  local code="$1" host
  # The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
  # For a QR code in the terminal, qrencode -t ansiutf8 draws this link.
  host="$(printf '%s' "$BASE_URL" | sed -E 's#^[a-z]+://([^/]+).*#\1#; s#^api\.#app.#')"
  printf '\n'
  printf "$TEXT_CODE" "${code:0:3}" "${code:3}" "$2"
  printf "$TEXT_LINK" "https://$host/verbinden?code=$code"
  printf '%s\n\n' "$TEXT_ENTER"
}

TOKEN=""
[[ -s "$TOKEN_FILE" ]] && TOKEN="$(tr -d '[:space:]' < "$TOKEN_FILE")"
PAIRED=""
EXPIRES=0

# With a stored token, ask first whether it still signs in; only 401 means it does not.
if [[ -n "$TOKEN" ]]; then
  failures=0
  while :; do
    status="$(call GET /device "$TOKEN")"
    case "$status" in
      200) PAIRED=1; break ;;
      401) break ;;
      429) sleep "$(retry_after)" ;;
      # A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
      4??) fail "$status" ;;
      *) failures=$((failures + 1)); pause_after_error "$failures" "HTTP $status" ;;
    esac
  done
fi

while [[ -z "$PAIRED" ]]; do
  # Ask for a code. Without a key the API answers 400, so stop here instead.
  key="$(new_key)"
  if [[ -z "$key" ]]; then echo "$TEXT_NO_KEY" >&2; exit 1; fi
  failures=0
  while :; do
    status="$(call POST /device-pairings "$TOKEN" "$key" '{"model":"Kickertisch-Beispiel","firmware":"1.0"}')"
    if [[ "$status" == 201 ]]; then
      TOKEN="$(jq -r '.data.token' "$BODY_FILE")"
      # Shown only this once: keep it before anything else.
      save_token "$TOKEN"
      expires_at="$(jq -r '.data.expires_at' "$BODY_FILE")"
      EXPIRES="$(jq -r '.data.expires_at | fromdateiso8601' "$BODY_FILE")"
      show_code "$(jq -r '.data.code' "$BODY_FILE")" "${expires_at:11:5}"
      break
    elif [[ "$status" == 409 && "$(problem)" == device_already_paired ]]; then
      EXPIRES=0
      break
    elif [[ "$status" == 409 && "$(problem)" == table_devices_off ]]; then
      echo "$TEXT_OFF"
      sleep 60
    elif [[ "$status" == 429 ]]; then
      sleep "$(retry_after)"
    elif (( status >= 500 )); then
      # The API is busy or being deployed: the same request with the same key, after a pause.
      failures=$((failures + 1))
      pause_after_error "$failures" "HTTP $status"
    else
      fail "$status"
    fi
  done

  # GET /device until it answers 200. Without a waiting code (EXPIRES 0) a 401 means the device
  # was unpaired: drop the token and ask for a new code without it. Only 401 means "not paired";
  # on a 5xx someone may be typing the code: keep it, ask again after a pause. Another 4xx is an error.
  failures=0
  while :; do
    status="$(call GET /device "$TOKEN")"
    if [[ "$status" == 200 ]]; then PAIRED=1; break; fi
    if [[ "$status" == 429 ]]; then sleep "$(retry_after)"; continue; fi
    if [[ "$status" == 4?? && "$status" != 401 ]]; then fail "$status"; fi
    if [[ "$status" != 401 ]]; then
      failures=$((failures + 1))
      pause_after_error "$failures" "HTTP $status"
      continue
    fi
    failures=0
    if [[ "$EXPIRES" == 0 ]]; then
      echo "$TEXT_UNPAIRED"
      TOKEN=""
      break
    fi
    if [[ "$(date +%s)" -ge "$EXPIRES" ]]; then
      echo "$TEXT_EXPIRED"
      break
    fi
    sleep "$POLL_SECONDS"
  done
done

jq -r "$TEXT_PAIRED" "$BODY_FILE"
