#!/bin/sh
set -eu

state=/var/lib/octava-firstboot
pending=$state/pending
completed=$state/completed
factory=/usr/share/octava-configd/factory
config=/var/lib/octava-configd
web=/var/lib/octava-web
credentials=/root/octava-firstboot-credentials
endpoint=/var/lib/octava-endpoint-controller

test -e "$pending" || exit 0
test "$(id -u)" -eq 0
install -d -m 0700 "$state" "$config"
install -d -m 0755 /usr/share/octava-configd

# systemd-networkd derives persistent link and DHCP client identifiers from
# machine-id while running as systemd-network.  A clean image deliberately
# ships an empty file, but it must stay world-readable after PID 1 fills it.
test -s /etc/machine-id
chmod 0444 /etc/machine-id

if ! test -s "$factory/manifest.json"; then
    rm -rf -- "$factory"
    /usr/local/libexec/octava-factory-materialize \
        --platform bpi-r4 --output-dir "$factory"
fi

if ! test -s "$config/config.db"; then
    rm -f -- "$config/config.db" "$config/config.db-journal" \
        "$config/config.initialized" "$config/config.lock"
    /usr/local/libexec/octava-config-provision \
        --state-dir "$config" --factory-dir "$factory"
fi

if ! test -s "$config/users.json"; then
    /usr/local/libexec/octava-identity-provision \
        --state-dir "$config" --credentials "$credentials"
fi

if ! test -s "$endpoint/learning.db"; then
    install -d -o octava-endpoint-controller -g octava-endpoint-controller -m 0700 "$endpoint"
    runuser -u octava-endpoint-controller -- \
        /usr/local/libexec/octava-endpoint-controller --provision \
        --state-directory="$endpoint"
fi

if ! test -s "$web/server.key" || ! test -s "$web/server.crt"; then
    rm -rf -- "$web"
    temporary=/var/lib/.octava-web-firstboot.$$
    trap 'rm -rf -- "$temporary"' EXIT HUP INT TERM
    /usr/local/libexec/octava-web --init --state-dir "$temporary" \
        --hosts localhost,127.0.0.1,192.168.255.1
    chown -R octava-web:octava-web "$temporary"
    chmod 0700 "$temporary"
    mv "$temporary" "$web"
    trap - EXIT HUP INT TERM
fi

rm -f "$web/bootstrap-password" "$pending"
printf 'schema=1\ncompleted=yes\n' >"$completed"
chmod 0600 "$completed"
sync -f "$state" "$config" "$web" "$factory" /etc/ssh /etc/machine-id
