#!/bin/bash

set -e

# first validate the arguments
REPLACE_FILE=false
for i in "$@" ; do
  case $i in
  --*-opts*)
    if ! echo $i | grep -E -- '--[a-zA-Z-]+?-opts=.+' > /dev/null 2>&1 ; then
      echo "Couldn't parse option $i expected --cmd-opts=-XX:+UseG1GC where cmd is hadoop-master or some such and -XX:+UseG1GC is the option to pass to the JVM" 1>&2 
      exit 1
    fi
  ;;
  --help)
    set +x
    echo "Usage: "
    echo "--<daemon>-opts"
    echo "   Set additional Java options for the specified daemon."
    echo " "
    echo "--replace"
    echo "   Replace the existing hbase-user-env.sh file if it exists."
    echo " "
    echo "<daemon> is one of:"
    echo "  hbase-master, hbase-regionserver, zookeeper"
    echo " "
    echo " "
    echo "Example Usage:"
    echo " --hbase-master-opts=-Xmx2048 --zookeeper-opts=-XX:GCTimeRatio=19"
    exit 1
  ;;
  --replace)
    REPLACE_FILE=true
  ;;
  *)
    echo "Unknown option $i" 1>&2
    exit 1
  ;;
  esac
done

set -x
mkdir /home/hadoop/conf
HBASE_ENV_FILE=/home/hadoop/conf/hbase-user-env.sh

if [ -d "/home/hadoop/hbase/conf" ] ; then
  HBASE_ENV_FILE=/home/hadoop/hbase/conf/hbase-user-env.sh
fi

if [ $REPLACE_FILE == "true" ] ; then
  rm -rf $HBASE_ENV_FILE
fi

if [ -e $HBASE_ENV_FILE ] ; then
  [[ ! -n $(grep "#\\!/bin/bash" $HBASE_ENV_FILE ) ]] && echo "#!/bin/bash" >> $HBASE_ENV_FILE
else
  echo "#!/bin/bash" >> $HBASE_ENV_FILE
fi

for i in "$@" ; do
  case $i in
  --*-opts*)
    OPTS_CMD=$(echo $i | sed -r 's|--(.*?)-opts=.*|\1|' | tr 'a-z-' 'A-Z_')_OPTS
    OPTS_VALUE=$(echo $i | sed -r 's|--.*?-opts=(.*)|\1|')
    cat >> $HBASE_ENV_FILE <<EOF
$OPTS_CMD="$OPTS_VALUE"
EOF
  ;;
  esac
done
