#!/bin/sh
set -e

PATH=/lib/infix/factory:$PATH

[ "$FACTORY_D" ] || FACTORY_D=/etc/auto-factory.d
[ "$CFG_D" ]     || CFG_D=/cfg
[ "$GENCFG_D" ]  || GENCFG_D=/cfg/factory.d
mkdir -p $GENCFG_D

gen-hostname   >$FACTORY_D/20-auto-hostname.json
gen-interfaces >$FACTORY_D/20-auto-interfaces.json

[ -s $GENCFG_D/20-auto-hostkey.json ] || gen-hostkeys >$GENCFG_D/20-auto-hostkey.json

# shellcheck disable=SC2046
jq -s 'reduce .[] as $item ({}; . * $item)' \
   $(find $FACTORY_D -name '*.json') \
   $(find $GENCFG_D  -name '*.json') \
    >$CFG_D/auto-factory-config.cfg

# TODO: Look for statically defined factory-config, based on the
# system's product ID.

# If we haven't found a better one, settle for auto-factory-config as
# the system's factory-config.
[ -h $CFG_D/factory-config.cfg ] || \
    ln -sf auto-factory-config.cfg $CFG_D/factory-config.cfg

# Bootstrap sysrepo db with all modules required by confd
sysrepo-bootstrap.sh $CFG_D/factory-config.cfg $CFG_D/startup-config.cfg
