#!/bin/bash
# @description create an admin user account
# @man This commands allows inserting a new user account. It is particularly useful
# @man to create the first admin account on the server. It requires that the
# @man authentication hash is bcrypt (default from fresh 6.1).
# @man +
# @man *Options*:
# @man +
# @man *-u*: specify the user name ("admin" by default)
# @man +
# @man *-p*: specify the user password (use with care as it is stored in history). Set the value to "" to use $ADMIN_PASSWORD from the environment instead

. "${BASEDIR}/../lib/common.sh"

set -o pipefail
set -e

USERFILE="${RUDDER_DIR}/etc/rudder-users.xml"
USER="admin"
PASS_OPT=""

while getopts "u:p:" opt; do
  case $opt in
    u)
      USER="${OPTARG}"
      ;;
    p)
      PASS_OPT="b"
      if [ "${OPTARG}" != "" ]; then
        ADMIN_PASSWORD="${OPTARG}"
      fi
      ;;
  esac
done

# check if user is already there
if grep -qE "name[[:space:]]*=[[:space:]]*\"${USER}\"" "${USERFILE}"
then
  echo "User '${USER}' already exists, aborting."
  exit 1
fi

if type argon2 >/dev/null 2>/dev/null
then
  # argon2id
  if [ -z "${ADMIN_PASSWORD}" ]; then
    read -p "Password: " -s ADMIN_PASSWORD
  fi
  hash=$(echo -n "${ADMIN_PASSWORD}" |  argon2 $(openssl rand 16) -id -e| tr -d ':\n')
else
  # bcrypt (12 cost)
  hash=$(htpasswd -n${PASS_OPT}BC 12 "" ${ADMIN_PASSWORD}| tr -d ':\n')
fi

details="<user name=\"${USER}\" password=\"${hash}\" permissions=\"administrator\" />"
sed -i "/^[[:space:]]*<\/authentication>/i ${details}" "${USERFILE}"

echo "User '${USER}' added, restarting the Rudder server"

systemctl restart rudder-jetty >/dev/null

