#!/bin/bash
# Copyright (c) 2019-2020, AT&T Intellectual Property. All rights reserved.
#
# Copyright (c) 2010-2011, 2015-2016 by Brocade Communications Systems, Inc.
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-only

BOOT_FILE=$1
shift

CAPI=/bin/cli-shell-api

do_commit () {
  cfgcli commit "$@"
}

umask 0002

(
  echo 'begin boot-config-loader'
  # set up config session
  SID=$$
  SENV=$($CAPI getSessionEnv $SID)
  eval "$SENV"
  if ! $CAPI setupSession; then
    echo 'Cannot set up configuration session.' 1>&2
    exit 1
  fi

  # do load
  echo 'begin load'
  if ! $CAPI loadFile "$BOOT_FILE"; then
    echo 'load finished with failure(s)' 1>&2
  else
    echo 'load finished successfully'
  fi

  # do commit
  echo 'begin commit'
  ret=0
  export COMMIT_VIA=boot-config-loader
  if ! do_commit ; then
    echo 'commit failed' 1>&2
    ret=1
  else
    echo 'commit succeeded'
  fi

  # clean up
  if ! $CAPI teardownSession; then
    echo 'teardown failed' 1>&2
  else
    echo 'teardown succeeded'
  fi
  echo 'end boot-config-loader'
  exit $ret
) </dev/null

exit $?

