#!/bin/bash

echo "YMC-CONFIG-PASSWORD-PROVIDER"

### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash || exit 1


if [ -z "$SOCAT_PEERADDR" ]; then
  echo "ERROR: Can not get your IP-address"
  sleep 2
  echo "GOODBYE"
  exit 1
fi

new_password=$(uuidgen)
if [ $? -ne 0 ] || \
   [ -z "$new_password" ]; then
  echo "ERROR: Can not generate passwords right now..."
  sleep 2
  echo "GOODBYE"
  exit 1
fi

remote_hostname_from_ip=$(ymc_get_ptr_full_hostname_for_ip $SOCAT_PEERADDR)
if [ $? -ne 0 ] || \
   [ -z "$remote_hostname_from_ip" ]; then
  echo "ERROR: Can not get a hostname for your IP-address '$SOCAT_PEERADDR'"
  sleep 2
  echo "GOODBYE"
  exit 1
fi

read remote_hostname_input
remote_hostname_transmitted=$(echo $remote_hostname_input | sed -r 's/^I AM://')
if [ "$remote_hostname_transmitted.cluster" != "$remote_hostname_from_ip" ]; then
  echo "ERROR: Based on our IP-address '$SOCAT_PEERADDR', you are not '$remote_hostname_transmitted'"
  sleep 2
  echo "GOODBYE"
  exit 1
fi
echo "YOU ARE:$remote_hostname_transmitted"

read action_input
echo "INFO: Adding password to svn's sasl-db..." 1>&2
echo "$new_password" | /usr/sbin/saslpasswd2 -c -f /data/ymc-cluster-ymc-config-server/auth/ymc-cluster-sasl.db -u "ymc-config.cluster" $remote_hostname_transmitted
if [ $? -ne 0 ]; then
  echo "ERROR: Failed to update the sasl-db at: /data/ymc-cluster-ymc-config-server/auth/ymc-cluster-sasl.db" 1>&2
  echo "ERROR: Failed to update password database"
  sleep 2
  echo "GOODBYE"
  exit 1
fi
echo "INFO: Successfully updated svn's sasl-db for $remote_host" 1>&2

echo "YOUR NEW PASSWORD:$new_password"
sleep 2

echo "GOODBYE"
exit 0
