#!/bin/bash -e

# Allow connector-local more time to start listening on socket
RANK=$(FLUX_LOCAL_CONNECTOR_RETRY_COUNT=30 flux getattr rank)

if ! content_backing=$(flux getattr content.backing-module 2>/dev/null); then
    content_backing=content-sqlite
fi

# Usage: modload {all|<rank>} modname [args ...]
modload() {
    local where=$1; shift
    if test "$where" = "all" || test $where -eq $RANK; then
        flux module load $*
    fi
}

modload all barrier
modload 0 ${content_backing}

modload all kvs
modload all kvs-watch

modload all resource
modload 0 cron sync=hb
modload 0 job-manager
modload 0 job-info

modload all job-ingest
modload 0 job-exec

core_dir=$(cd ${0%/*} && pwd -P)
all_dirs=$core_dir${FLUX_RC_EXTRA:+":$FLUX_RC_EXTRA"}
IFS=:
shopt -s nullglob
for rcdir in $all_dirs; do
    for rcfile in $rcdir/rc1.d/*; do
	echo running $rcfile
        $rcfile
    done
done
shopt -u nullglob

# Print module that has registered 'sched' service, if any
lookup_sched_module() {
    flux module list | awk '$6 == "sched" { print $1 }'
}

if test $RANK -eq 0 -a "${FLUX_SCHED_MODULE}" != "none" \
                    -a -z "$(lookup_sched_module)"; then
    flux module load ${FLUX_SCHED_MODULE:-sched-simple}
fi

test $RANK -ne 0 || flux admin cleanup-push <<-EOT
	flux queue stop --quiet
	flux job cancelall --user=all --quiet -f --states RUN
	flux queue idle --quiet
EOT
