#!/bin/sh
#
# inituserpwd - 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`

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

if [ -z "$THE_USER" ]; then
  echo "usage: inituserpwd username password" >&2
  exit 1
fi

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

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

