#!/bin/sh
# load [-b] <startup-config | failure-config>
#
# Import a configuration to the sysrepo datastore using `sysrepocfg -Ifile`
#
# If the '-b' option is used we set the Finit <usr/bootstrap> condition if
# sysrepocfg returns OK.  This to be able to detect and trigger the Infix
# Fail Secure Mode at boot.
#
set -e

banner_append()
{
    printf "\n$@\n" | tee -a \
			  /etc/banner \
			  /etc/issue \
			  /etc/issue.net \
			  >/dev/null
    return 0
}


# shellcheck disable=SC1091
. /etc/confdrc

config=$1
if [ -f "$config" ]; then
    fn="$config"
else
    if [ -f "$CFG_PATH_/${config}.cfg" ]; then
	fn="$CFG_PATH_/${config}.cfg"
    else
	fn="$SYS_PATH_/${config}.cfg"
    fi
fi

if [ ! -f "$fn" ]; then
    logger -sik -p user.error "No such file, $fn, aborting!"
    exit 1
fi

if ! sysrepocfg -v3 -I"$fn" -f json; then
    case "$config" in
	startup-config)
	    logger -sik -p user.error "Failed loading $fn, reverting to Fail Secure mode!"
	    ;;
	failure-config)
	    logger -sik -p user.error "Failed loading $fn, aborting!"
	    banner_append "CRITICAL ERROR: Logins are disabled, no credentials available"
	    initctl -nbq runlevel 9
	    ;;
    esac

    exit 1
fi
logger -sik -p user.notice "Loaded $fn successfully."
if [ "$config" = "failure-config" ]; then
    banner_append "ERROR: Corrupt startup-config, system has reverted to default login credentials"
fi
