#!/bin/sh

[ $# -ne 2 ] && echo "Usage: $0 <username> <namespace>" && exit 1

USERNAME=$1
NAMESPACE=$2

if [ "$(systemctl is-active mongod)" != "active" ]; then
        echo "ERROR: mongoDB service is not running"
        exit 1  
fi


ID=`mongo main --quiet --eval "JSON.stringify(db.users.findOne({ name:'$USERNAME' }))" | jq -r '._id."$oid" // empty'`

if [ -z "$ID" ]; then
    echo "ERROR: user does not exists!"
    exit 1
fi

TENANT_ID=`mongo main --quiet --eval "JSON.stringify(db.namespaces.findOne({ name:'$NAMESPACE' }))" | jq -r '.tenant_id // empty'`

if [ -z "$TENANT_ID" ]; then
    echo "ERROR: namespace does not exists!"
    exit 1
fi

MODIFIED=`mongo main --quiet --eval "db.namespaces.updateOne({ tenant_id: '$TENANT_ID' }, { \\$pull: { members: '$ID' } }).modifiedCount"`

if [ $MODIFIED -eq 1 ]; then
    echo "User $USERNAME removed from namespace $NAMESPACE"
else
    echo "ERROR: Failed to remove user from namespace"
fi
