#!/usr/bin/env bash
# 
# Print the users who have access to a given 1Password item.
#
# Usage:
# 
#   1pw-item-users "$ITEM_NAME"
#
# Note, the `op` tool must be authenticated before this command is run.

function main {
    local item_name="$1"

    # Determine the vault ID for the passed item.
    local vault_id
    vault_id=$(vault_id "$item_name")

    # Print the unique emails from the combined lists of direct- and group-linked users.
    (vault_direct_user_emails "$vault_id" ; vault_group_user_emails "$vault_id") | sort | uniq
}

# Print the vault ID for the given item name.
function vault_id {
    op item get --format=json "$1" | jq -r '.vault.id'
}

# Print a list of user emails who have DIRECT access to a vault (the vault ID is passed).
function vault_direct_user_emails {
    op vault user list --format=json "$1" | jq -r '.[].email'
}

# Print a list of user emails who have GROUP access to a vault (the vault ID is passed).
function vault_group_user_emails {
    op vault group list --format=json "$1" | jq -r '.[] | .id' | while read -r group_id; 
    do 
        op group user list --format=json "$group_id" | jq -r '.[].email'; 
    done                        
}

main "$@"