#!/bin/sh
# Show StoreCast's web address, and the first-run setup code until setup is done, on the
# console login screen (agetty reads /run/issue.d).
set -e
code_file=${STORECAST_SETUP_CODE:-/var/lib/storecast/setup-code}
out=${STORECAST_ISSUE:-/run/issue.d/50-storecast.issue}
# At boot StoreCast writes the code a moment after it starts; give it time to appear.
wait=${STORECAST_WAIT:-20}
while [ ! -s "$code_file" ] && [ "$wait" -gt 0 ]; do
    sleep 1
    wait=$((wait - 1))
done
mkdir -p "$(dirname "$out")"
{
    printf '%s\n' "JPPS StoreCast"
    # \4 is agetty's escape for this box's IPv4 address.
    printf '%s\n' '  Open in a browser on this network:  http://\4/'
    if [ -s "$code_file" ]; then
        printf '  First-time setup code:  %s\n' "$(tr -cd '0-9-' < "$code_file")"
    fi
    printf '\n'
} > "$out.tmp"
mv "$out.tmp" "$out"
if command -v agetty >/dev/null 2>&1; then agetty --reload >/dev/null 2>&1 || true; fi
