#!/bin/bash

# Requirements: jq, python, and `pip install -r requirements.txt`
# Usage: ./check-did.sh [did]
# If no DID provided, lists all visible DIDs

API_URL=${ENDORSER_API_URL:-"https://test-api.endorser.ch/api"}
ADMIN_DID="did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F"
ADMIN_KEY="2b6472c026ec2aa2c4235c994a63868fc9212d18b58f6cbfe861b52e71330f5b"

# Create verification JWT using Python (equivalent to uport-credentials)
jwt=$(python3 -c "
from eth_keys import keys
import hashlib, base64, json, time

# Create header and payload
header = {'typ': 'JWT', 'alg': 'ES256K'}
payload = {
    'iss': '$ADMIN_DID',
    'exp': int(time.time()) + 300  # 5 minutes from now
}

# Base64url encode header and payload
def b64url(data):
    return base64.urlsafe_b64encode(json.dumps(data).encode()).decode().rstrip('=')

header_b64 = b64url(header)
payload_b64 = b64url(payload)
message = f'{header_b64}.{payload_b64}'

# Sign using admin key
private_key = keys.PrivateKey(bytes.fromhex('$ADMIN_KEY'))
message_hash = hashlib.sha256(message.encode()).digest()
signature = private_key.sign_msg_hash(message_hash)
signature_bytes = signature.r.to_bytes(32, 'big') + signature.s.to_bytes(32, 'big')
signature_b64 = base64.urlsafe_b64encode(signature_bytes).decode().rstrip('=')

# Output complete JWT
print(f'{message}.{signature_b64}')
")

REQUEST_URL="$API_URL/report/whichDidsICanSee"
echo "Making request to: $REQUEST_URL"
echo "Getting visible DIDs..."
response=$(curl -s -X GET "$REQUEST_URL" \
     -H "Authorization: Bearer $jwt" \
     -H "Content-Type: application/json")

echo -e "\nResponse:"
echo "$response" | jq '.'

# If specific DID provided, check if it's in the list
if [ -n "$1" ]; then
    echo -e "\nChecking if DID $1 is visible..."
    if echo "$response" | jq -e --arg did "$1" '.[] | select(. == $did)' > /dev/null; then
        echo "✅ DID is registered and visible"
    else
        echo "❌ DID not found in visible list"
    fi
fi