#!/bin/sh
# Make this machine a DUR build node (package dur-worker): with the
# activation token a DUR admin or moderator gave out (it counts once and
# for a limited time), read from standard input or asked for on the
# terminal without echo, never as an argument.
#   dur-worker-enroll [<api-url>]
# The API defaults to API_URL in /etc/dur/worker.conf.  Run as root.
set -eu
[ "$(id -u)" -eq 0 ] || { echo "dur-worker-enroll: run as root" >&2; exit 1; }
API_URL=
[ ! -r /etc/dur/worker.conf ] || . /etc/dur/worker.conf
api=${1:-$API_URL}
[ -n "$api" ] || { echo "dur-worker-enroll: no API URL (/etc/dur/worker.conf)" >&2; exit 1; }
if [ -s /etc/debusine/worker/token ]; then
    echo "dur-worker-enroll: this node is registered already" >&2
    exit 1
fi
if [ -t 0 ]; then
    printf 'Activation token: '
    stty -echo
    trap 'stty echo' EXIT
    read -r token
    stty echo
    trap - EXIT
    echo
else
    read -r token
fi
[ -n "$token" ] || { echo "dur-worker-enroll: no token" >&2; exit 1; }
printf '%s\n' "$token" | sh /usr/share/dur/worker/scripts/setup-worker.sh "$api" -
