#!/bin/bash

userName=$1
firstName=$2
lastName=$3
email=$4
password=$5

credentials="admin:alfrescodevops"

alfresco_base_url="http://localhost:8070/alfresco"
alfresco_url="$alfresco_base_url/service/api/people"

disable_admin_cmd="curl -H \"Accept: application/json\" -H \"Content-type: application/json\" -X PUT -d '{\"disableAccount\":true}' --user admin:admin $alfresco_url/admin"

# Wait until alfresco is up
until $(curl --output /dev/null --silent --head --fail $alfresco_base_url); do
    printf '.'
    sleep 5
done

user_exists=`curl -o /dev/null -w "%{http_code}" -u$credentials $alfresco_url/$userName`

if [ "$user_exists" -eq "404" ]
then

cat > alfresco-user.json <<-EOL
{
"userName" : "$userName",
"firstName" : "$firstName",
"lastName" : "$lastName",
"email" : "$email",
"password" : "$password",
"groups" : ["GROUP_ALFRESCO_ADMINISTRATORS"]
}
EOL

curl  -u$credentials --silent -i -H "Content-Type: application/json" -X POST --data @alfresco-user.json $alfresco_url

# TODO - still not working
# $disable_admin_cmd

rm -f alfresco-user.json
fi
