#!/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
}

note()
{
    logger -s -I $$ -p user.notice -t load "$*"
}

err()
{
    logger -s -I $$ -p user.error -t load "$*"
}


# 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
    err "No such file, $fn, aborting!"
    exit 1
fi

note "Loading $config ..."
if ! sysrepocfg -v3 -I"$fn" -f json; then
    case "$config" in
	startup-config)
	    err "Failed loading $fn, reverting to Fail Secure mode!"
	    # On failure to load startup-config the system is in an undefined state
	    cat <<-EOF >/tmp/factory.json
		{
		   "infix-factory-default:factory-default": {}
		}
		EOF
	    # Default timeout is 2 seconds, allow time to clean up shm
	    if ! sysrepocfg -f json -t 10 -R /tmp/factory.json; then
		rm -f /etc/sysrepo/data/*startup*
		rm -f /etc/sysrepo/data/*running*
		rm -f /dev/shm/sr_*
		killall sysrepo-plugind
	    fi
	    ;;
	failure-config)
	    err "Failed loading $fn, aborting!"
	    banner_append "CRITICAL ERROR: Logins are disabled, no credentials available"
	    initctl -nbq runlevel 9
	    ;;
    esac

    exit 1
fi

note "Loaded $fn successfully."
if [ "$config" = "failure-config" ]; then
    banner_append "ERROR: Corrupt startup-config, system has reverted to default login credentials"
else
    # Ensure correct ownership and permissions, in particular after factory reset
    # Created by the system, writable by any user in the admin group.
    chown root:wheel "$fn"
    chmod 0660 "$fn"
fi
