#!/bin/sh
# SPDX-License-Identifier: MIT
# ntfy on the bench: the accounts of a profile, created as in the guide, with the ntfy command
# line inside the container. Runs in the measured container, in /opt/banc/app.
#
#   comptes.sh 0     idle profile: the first admin account only
#   comptes.sh N     N subscribers (read access to 3 topics each), N scripts (write access to
#                    their own topic, one token each) and the account that loads the dataset
#
# Writes /opt/banc/comptes.json for the load generator.
set -eu
N=$1
cd /opt/banc/app

docker compose exec -T -e N="$N" ntfy sh -s > /opt/banc/comptes.txt <<'EOF'
set -eu
mdp() { head -c 18 /dev/urandom | base64 | tr -d '/+=\n'; }
two() { printf '%02d' "$1"; }
NTFY_PASSWORD="$(mdp)" ntfy user add --role=admin banc-admin >/dev/null 2>&1
[ "$N" -eq 0 ] && exit 0
i=0
while [ "$i" -lt "$N" ]; do
  p="$(mdp)"
  NTFY_PASSWORD="$p" ntfy user add "abonne-$(two $i)" >/dev/null 2>&1
  for k in 0 1 2; do
    ntfy access "abonne-$(two $i)" "banc-$(two $(( (i + k) % N )))" read-only >/dev/null 2>&1
  done
  echo "abonne $i $p"
  NTFY_PASSWORD="$(mdp)" ntfy user add "script-$(two $i)" >/dev/null 2>&1
  ntfy access "script-$(two $i)" "banc-$(two $i)" write-only >/dev/null 2>&1
  t="$(ntfy token add --label=banc "script-$(two $i)" 2>&1 | sed -n 's/.*\(tk_[A-Za-z0-9]*\).*/\1/p')"
  echo "script $i $t"
  i=$((i + 1))
done
NTFY_PASSWORD="$(mdp)" ntfy user add banc-semis >/dev/null 2>&1
ntfy access banc-semis 'banc-*' write-only >/dev/null 2>&1
t="$(ntfy token add --label=banc banc-semis 2>&1 | sed -n 's/.*\(tk_[A-Za-z0-9]*\).*/\1/p')"
echo "semis 0 $t"
EOF

two() { printf '%02d' "$1"; }
{
  echo '{"base":"http://10.30.0.207:2586","ws":"ws://10.30.0.207:2586","abonnes":['
  sep=''
  while read -r kind i secret; do
    [ "$kind" = abonne ] || continue
    t0=$(two $i); t1=$(two $(( (i + 1) % N ))); t2=$(two $(( (i + 2) % N )))
    printf '%s{"user":"abonne-%s","pass":"%s","topics":["banc-%s","banc-%s","banc-%s"],"ip":"198.18.0.%d"}' \
      "$sep" "$(two $i)" "$secret" "$t0" "$t1" "$t2" $((i + 1))
    sep=','
  done < /opt/banc/comptes.txt
  echo '],"scripts":['
  sep=''
  while read -r kind i secret; do
    [ "$kind" = script ] || continue
    printf '%s{"token":"%s","topic":"banc-%s","ip":"198.18.1.%d"}' "$sep" "$secret" "$(two $i)" $((i + 1))
    sep=','
  done < /opt/banc/comptes.txt
  echo '],"semis":'
  semis=$(awk '$1 == "semis" {print $3}' /opt/banc/comptes.txt)
  printf '{"token":"%s","ip":"198.19.255.250"}}\n' "$semis"
} > /opt/banc/comptes.json
jq -e '(.abonnes | length) == (.scripts | length)' /opt/banc/comptes.json >/dev/null
rm -f /opt/banc/comptes.txt
