#!/usr/bin/env bash
# Copyright (c) HashiCorp, Inc.
# SPDX-License-Identifier: MPL-2.0


# The new key will be on a file generated by consul-template
# the script retrieves the key from the file

NEW_KEY=`cat /opt/consul/gossip/gossip.key | sed -e '/^$/d'`

# Install the key

consul keyring -install ${NEW_KEY}

# Set as primary

consul keyring -use ${NEW_KEY}

# Check other keys

KEYS=`curl -s localhost:8500/v1/operator/keyring`

# Example output for the call:
# {
#   "WAN": true,
#   "Datacenter": "dc1",
#   "Segment": "",
#   "Keys": {
#     "9tqwmqyncZtWV4UmainmdY2e8xZu0Cv8Eugq4Mku0EU=": 1,
#     "CYq+j4wGJ+GD7gGrmF1maUQIsrOd4MKRC20O4lG1FGQ=": 1
#   },
#   "PrimaryKeys": {
#     "9tqwmqyncZtWV4UmainmdY2e8xZu0Cv8Eugq4Mku0EU=": 1
#   },
#   "NumNodes": 1
# }
# {
#   "WAN": false,
#   "Datacenter": "dc1",
#   "Segment": "",
#   "Keys": {
#     "9tqwmqyncZtWV4UmainmdY2e8xZu0Cv8Eugq4Mku0EU=": 1,
#     "CYq+j4wGJ+GD7gGrmF1maUQIsrOd4MKRC20O4lG1FGQ=": 1
#   },
#   "PrimaryKeys": {
#     "9tqwmqyncZtWV4UmainmdY2e8xZu0Cv8Eugq4Mku0EU=": 1
#   },
#   "NumNodes": 1
# }

#  <!-- Primary keys -->
# This should only return one single key
P_KEY=`echo ${KEYS} | jq -r '.[].PrimaryKeys| to_entries[].key' | sort | uniq`

# Check if key is primary 

# <!-- All Keys -->
ALL_KEYS=`echo ${KEYS} | jq -r '.[].Keys| to_entries[].key' | sort | uniq`

for i in `echo ${ALL_KEYS}`; do
  if [ $i != ${NEW_KEY} ] ; then
    consul keyring -remove $i
  fi
done
