#!/bin/sh
# SPDX-License-Identifier: MIT
# Node-RED on the bench: the first account, as the security documentation describes it
# (https://nodered.org/docs/user-guide/runtime/securing-node-red): an `adminAuth` user with full
# permissions and a bcrypt password, added to the settings file Node-RED wrote at its first start,
# then a restart. Runs in the measured container, in /opt/banc/app. Node-RED has no other account:
# the simulated users of the profiles are the devices that feed its flows.
#
#   comptes.sh N     writes /opt/banc/comptes.json for the load generator
set -eu
N=$1
cd /opt/banc/app
until [ -f data/settings.js ]; do sleep 1; done
P=$(head -c 18 /dev/urandom | base64 | tr -d '/+=\n')
H=$(docker compose exec -T -w /usr/src/node-red -e P="$P" node-red node -e "console.log(require('bcryptjs').hashSync(process.env.P, 8))")
mv data/settings.js data/settings.base.js
cat > data/settings.js <<FIN
// Bench: the settings file Node-RED wrote at its first start (settings.base.js), with the first
// admin account, as the security documentation describes it.
const settings = require('./settings.base.js');
settings.adminAuth = { type: 'credentials', users: [{ username: 'banc-admin', password: '$H', permissions: '*' }] };
module.exports = settings;
FIN
chown 1000:1000 data/settings.js data/settings.base.js
docker compose restart node-red >/dev/null 2>&1
until [ "$(curl -s -m 1 -o /dev/null -w '%{http_code}' http://10.30.0.207:1880/settings || true)" = 401 ]; do sleep 0.5; done
printf '{"base":"http://10.30.0.207:1880","ws":"ws://10.30.0.207:1880","user":"banc-admin","pass":"%s","n":%d}\n' "$P" "$N" > /opt/banc/comptes.json
