#!/bin/bash

# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

FILENAME=/etc/clearwater/fallback_ifcs.xml
SCHEMA=/usr/share/clearwater/clearwater-config-manager/scripts/config_validation/fallback_ifcs_schema.xsd

[ $# -le 1 ] || { echo "Usage: validate_fallback_ifcs_xml [file to validate] (defaults to $FILENAME if not specified)" >&2 ; exit 2 ; }
[ -z "$1" ] || FILENAME=$1

# Check that the file to validate is present.
if [[ ! -f $FILENAME ]]
then
    echo "No configuration file at $FILENAME, unable to validate."
    exit 2
fi

xmllint --format --pretty 1 --load-trace --debug --schema $SCHEMA $FILENAME 2> /tmp/validate-fallback-ifcs-xml.stderr.$$ > /tmp/validate-fallback-ifcs-xml.stdout.$$
rc=$?

# Check the return code and log if appropriate.
if [ $rc != 0 ] ; then
  echo The fallback iFC sets file is invalid.                        >&2
  cat /tmp/validate-fallback-ifcs-xml.stderr.$$ | grep -v "Loaded URL" >&2
else
  echo The fallback iFCs configuration is valid.
fi

rm -f /tmp/validate-fallback-ifcs-xml.stderr.$$ /tmp/validate-fallback-ifcs-xml.stdout.$$

exit $rc
