#!/bin/sh
# Jetable. La matrice d'accès de /team, sur le port réellement en écoute.
set -eu

BASE=http://127.0.0.1:4214
JAR=$(mktemp -d)

signin() {
  curl -s -c "$JAR/$1.txt" -H 'Content-Type: application/json' \
    -d "{\"username\":\"$1\",\"password\":\"$2\"}" \
    "$BASE/api/auth/sign-in/username" > /dev/null
}

signin narin admin1
signin malai manager1
signin nattikan staff1

printf '%-34s %-14s %-14s %s\n' route admin manager staff
for route in /team '/team?dept=Casting' '/team?dept=RienDuTout' '/team?dept='; do
  a=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR/narin.txt" "$BASE$route")
  m=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR/malai.txt" "$BASE$route")
  s=$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' -b "$JAR/nattikan.txt" "$BASE$route")
  printf '%-34s %-14s %-14s %s\n' "$route" "$a" "$m" "$s"
done

body() {
  curl -s -b "$JAR/$1.txt" "$BASE$2" \
    | sed -n 's/.*<main[^>]*>\(.*\)<\/main>.*/\1/p' \
    | sed 's/<[^>]*>/\n/g' | grep -v '^[[:space:]]*$'
}

echo
echo "=== ce que voit le responsable de son propre departement ==="
body malai /team | head -12

echo
echo "=== le meme, demandant Casting par l'URL ==="
body malai '/team?dept=Casting' | head -4

rm -rf "$JAR"
