#!/bin/sh

set -eu

# This script fetches device.json for netbooting devices.

# Do nothing unless we have booted with NBD.
test -e /run/puavo/nbd-server || exit 0

status=0

# XXX we could also figure this out from another source?
# XXX could this be asked from the boot server maybe?
PUAVO_CERT_VERSION=$(jq -r '.["puavo.admin.certs.versions"]' \
                       /etc/puavo-conf/image.json | awk '{ print $1 }')
if [ -z "$PUAVO_CERT_VERSION" ]; then
  echo 'could not figure out the admin cert version' >&2
  exit 1
fi

url="$(env PUAVO_CERT_VERSION="$PUAVO_CERT_VERSION" \
         puavo-resolve-api-server --no-cloud-fallback)/v3/devices/$(hostname -s)"

# Get device settings.
# Set --max-time to 30 seconds to allow the boot to continue in case of
# failure; so we can check out later (with ssh or some such) what went wrong.
if curl --cacert /etc/puavo-conf/rootca.pem  \
        --header 'Authorization: Bootserver' \
        --fail                               \
        --max-time 30                        \
        --silent                             \
        "$url" > /etc/puavo/device.json.tmp; then
  mv /etc/puavo/device.json.tmp /etc/puavo/device.json
else
  rm -f /etc/puavo/device.json.tmp
  status=1
fi

exit $status
