#!/bin/sh
#
# inituser - add a user using their corresponding certificate
#
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`

FILES=
for i 
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)}'`

  cat > $DB/data/user-$THE_USER.json <<EOF
{
  "usr": [
    {"username": "$THE_USER", "cert": "$THE_CERT", "member_of": ["default user group"] },
  ]
}
EOF
  FILES="$FILES $DB/data/user-$THE_USER.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

