#!/bin/bash

# Copyright (C) Metaswitch Networks
# 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/chronos/chronos_shared.conf
local_site_name=site1
etcd_key=clearwater
. /etc/clearwater/config

. /usr/share/clearwater/utils/check-root-permissions 2

# Check we can contact `etcd`
if ! nc -z ${management_local_ip:-$local_ip} 4000
then
  echo "The Clearwater Configuration store (etcd) is not running"
  echo "Please start it before uploading configuration"
  exit 2
fi

# Check that there's chronos shared configuration to upload
if [[ ! -f $FILENAME ]]
then
  echo "No Chronos shared configuration detected"
  exit 2
fi

# Upload the file to etcd
keypath=http://${management_local_ip:-$local_ip}:4000/v2/keys/$etcd_key/$local_site_name/configuration/chronos_shared_config
curl -X PUT $keypath --data-urlencode value@$FILENAME 2> /tmp/upload-chronos-shared-config.stderr.$$ | tee /tmp/upload-chronos-shared-config.stdout.$$ | egrep -q "\"action\":\"set\""
rc=$?

# Check the return code and log if appropriate.
if [ $rc != 0 ] ; then
  echo Upload chronos shared configuration failed to $keypath  >&2
  cat /tmp/upload-chronos-shared-config.stderr.$$              >&2
  cat /tmp/upload-chronos-shared-config.stdout.$$              >&2
else
  # Add this node to the list of nodes to restart
  /usr/share/clearwater/clearwater-queue-manager/scripts/modify_nodes_in_queue add apply_chronos_shared_config
fi
rm -f /tmp/upload-chronos-shared-config.stderr.$$ /tmp/upload-chronos-shared-config.stdout.$$

exit $rc
