#!/bin/sh
#
# initusercertpwd - add a user using their corresponding certificate 
#		    and also enable a password 
#
# kmip_server_usr_01 can also be used to set or change a password
#
# e.g.
#
# ./run kmip_server_usr_01 mod part=partition username=the_username \
#		password=the_password
#
#

HERE=`pwd`
BIN=`dirname $0`

DONT=0
if [ "$1" = "-n" ]; then
  DONT=1
  shift
fi

cd $BIN

if [ -d db ]; then 
  DB=db
  else if [ -d ../db ]; then 
    DB=../db
  fi
fi

TOP=`dirname $DB`

THE_USER="$1"
THE_PASS="$2"

# the username can be provided as an optional overriding argument so it is
# used rather than the CN from the certificate
THE_USERNAME="$3"

FILES=
for i in $THE_USER
do
  case $i in
    *crt|*pem|*PEM) FORMAT="";;
    *) FORMAT="-inform der";;
  esac
  THE_USER=`openssl x509 $FORMAT -in $i -subject -noout -nameopt multiline |sed -e 's/\r//g' | grep commonName  | awk -F= '{print $2}' | awk '{print $1}'`
  THE_CERT=`openssl x509 $FORMAT -in $i -outform d | openssl base64 -a -e |sed -e 's/\r//g' | awk '{printf("%s",$1)}'`

  if [ -z "$THE_USERNAME" ]; then 
    THE_USERNAME="$THE_USER"
  fi

  cat > $DB/data/user-$THE_USERNAME.json <<EOF
{
  "usr": [
    {"username": "$THE_USERNAME", "cert": "$THE_CERT", "password": "$THE_PASS", "member_of": ["default user group"] },
  ]
}
EOF
  FILES="$FILES $DB/data/user-$THE_USERNAME.json"
done

LOAD=
for i in $FILES
do
  LOAD="$LOAD load=$i"
done

# 
# load in the newly created file for this user and ensure that the
# DB log is on so that we will see any failure details in terms of
# unique key constraints (e.g. attempts to use the same certificate for
# more than one user)
#
if [ "$DONT" = "1" ]; then
  echo ./run k_db db.log=true top=$TOP $LOAD
else
  exec ./run k_db db.log=true top=$TOP $LOAD
fi

