function usage() {
    cmd=$1
    echo "usage: ${cmd} [-u | --user <user name>] [-p | --pass <password>] [-s | --server_url <server url>]"
    echo
    echo "example: ${cmd} -u Administrator -p Administrator -s http://localhost:8080"
}

# parse command line
while [[ $# -gt 0 ]]
do
    case $1 in
	-u|--user)
	    USERID="$2"
	    shift
	    shift
	    ;;
	-p|--password)
	    PASSWORD="$2"
	    shift
	    shift
	    ;;
	-s|--server_url)
	    SERVERURL="$2"
	    shift
	    shift
	    ;;
	*)
	    echo "unknown option: ${1}"
	    usage $(basename $0)
	    exit 1
	    ;;
esac
done

if [ -z "${USERID}" -o -z "${PASSWORD}" -o -z "${SERVERURL}" ]
then
    usage $(basename $0)
    exit 1
fi

DOC_NAME=RetentionRules
DOC_PATH=/${DOC_NAME}
PARENT_PATH=/

set -x

#
# create RetentionRules folder
#

curl -X POST "${SERVERURL}/nuxeo/api/v1/path${PARENT_PATH}" -H "Content-Type: application/json" -u ${USERID}:${PASSWORD}  -d '
{
    "entity-type": "document",
    "type": "'${DOC_NAME}'",
    "name": "'${DOC_NAME}'",
    "title": "'${DOC_NAME}'",
    "properties": {
	"dc:title": "'${DOC_NAME}'"
    }
}'

#
# add ACLs matching https://github.com/nuxeo/nuxeo-retention/blob/lts-2021/nuxeo-retention/src/main/resources/OSGI-INF/retention-content-template.xml
#

curl -X POST "${SERVERURL}/nuxeo/site/automation/Document.BlockPermissionInheritance" -u ${USERID}:${PASSWORD} -H 'X-NXRepository: default' -H 'X-NXVoidOperation: false' -H 'content-type: application/json' -d '{
    "params": {
	"acl": "local"
    },
    "input": "'${DOC_PATH}'",
    "context": {}
}'

curl -X POST "${SERVERURL}/nuxeo/site/automation/Document.AddPermission" -u ${USERID}:${PASSWORD} -H 'X-NXRepository: default' -H 'X-NXVoidOperation: false' -H 'content-type: application/json' -d '{
    "params": {
	"permission": "Everything",
	"acl": "local",
	"username": "RecordManager"
    },
    "input": "'${DOC_PATH}'",
    "context": {}
}'

