#!/usr/bin/env bash
# Manage users via authelia-api
# Usage: ./manage-users.sh list
#        ./manage-users.sh create username displayname email groups...
#        ./manage-users.sh delete username

API_BASE="http://127.0.0.1:8080"
TOKEN=$(grep -oP 'session_secret: \K.*' /opt/nextworkspace/config/authelia/configuration.yml)

case "${1:-}" in
    list)
        curl -s -H "Authorization: Bearer $TOKEN" "$API_BASE/api/users" | jq . 2>/dev/null || \
        curl -s -H "Authorization: Bearer $TOKEN" "$API_BASE/api/users"
        ;;
    create)
        shift
        if [ $# -lt 3 ]; then
            echo "Usage: $0 create username displayname email [groups...]" >&2
            exit 1
        fi
        USERNAME="$1"; DISPLAY="$2"; EMAIL="$3"; shift 3
        GROUPS='["users"'
        for g in "$@"; do GROUPS="$GROUPS,\"$g\""; done
        GROUPS="$GROUPS]"
        curl -s -X POST -H "Authorization: Bearer $TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"users\":[{\"username\":\"$USERNAME\",\"display_name\":\"$DISPLAY\",\"email\":\"$EMAIL\",\"groups\":$GROUPS}]}" \
            "$API_BASE/api/users/bulk"
        ;;
    delete)
        if [ -z "${2:-}" ]; then
            echo "Usage: $0 delete username" >&2
            exit 1
        fi
        curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \
            "$API_BASE/api/users/$2"
        ;;
    *)
        echo "Usage: $0 {list|create|delete} ..." >&2
        exit 1
        ;;
esac
