#!/bin/bash
################################################################################
# Copyright (c) 2011-2016 VMware, Inc. All rights reserved.
################################################################################
# Sets up a replication user on master

ENCODING=UTF8
THIS_DIR=`dirname $0`

if [ -z $VMWARE_POSTGRES_BASE ]; then
   echo "VMWARE_POSTGRES_BASE is not set."
   echo "Check your installation."
   exit 1
fi
SANITY_FILE=$VMWARE_POSTGRES_BASE/scripts/vpostgres_sanity_checks
if [ -f $SANITY_FILE ]; then
   source $SANITY_FILE
else
   echo "Sanity check file for environment variables of VMware Postgres"
   echo "is not available. Check your installation."
   exit 1
fi

USERNAME=$1
if [ -z "$USERNAME" ]; then
   echo "Usage: $0 <username>"
   exit 1
fi

PASSWORD=
while [ "$PASSWORD" == "" ]; do
   read -p "Password: " -r -s p1 && echo && \
   read -p "Retype password: " -r -s p2 && echo
   if [ $? != 0 ]; then
      echo Password input error.
   elif [ "$p1" != "$p2" ]; then
      echo Passwords do not match
   elif [ "$p1" == "" ]; then
      echo Password is empty
   else
      PASSWORD=$p1
   fi
done

# Create user having both REPLICATION and LOGIN rights to be able to
# take base backups as well as run replication on it.
$VMWARE_POSTGRES_BIN/psql -c "create user \"$USERNAME\" password '`sed "s/'/''/g" <<<"$PASSWORD"`' replication login"
