#!/bin/bash
# The create-time setup script of a hosted server runs this as the sandbox user, with the sandbox
# env that the account server set. boat does not give that env to systemd, so this copies the two
# hosted variables to a 0600 file that openbot-hosted-server waits for.
#
# The claim stays in the file after the first start. Until its first use, each start of the server makes it work for
# one hour. After its first use it works for 10 minutes. OpenBot removes it from the environment that agents inherit.
set -euo pipefail
umask 077

[[ ${OPENBOT_HOSTED_HOST_ID:-} =~ ^[0-9a-fA-F-]{36}$ ]] || { echo "OPENBOT_HOSTED_HOST_ID is missing." >&2; exit 1; }
[ -n "${OPENBOT_HOSTED_CLAIM:-}" ] || { echo "OPENBOT_HOSTED_CLAIM is missing." >&2; exit 1; }
[[ $OPENBOT_HOSTED_CLAIM =~ ^[A-Za-z0-9_-]+$ ]] || { echo "OPENBOT_HOSTED_CLAIM is not valid." >&2; exit 1; }

directory="$HOME/.config/openbot-hosted"
mkdir -p "$directory"
chmod 0700 "$directory"
temporary=$(mktemp "$directory/env.XXXXXX")
printf 'OPENBOT_HOSTED_HOST_ID=%s\nOPENBOT_HOSTED_CLAIM=%s\n' "$OPENBOT_HOSTED_HOST_ID" "$OPENBOT_HOSTED_CLAIM" >"$temporary"
mv -f "$temporary" "$directory/env"
