#!/bin/bash

# ----------------Configuration-----------------
# CRITICAL: Replace "YourSecretKeyHere" with your actual static-auth-secret
SECRET="j@mk@Z@3"
IDENTIFIER="testuser1"
DURATION=86400 # Validity duration in seconds (e.g., 600 = 10 minutes)
SERVER_IP="198.58.104.114"
# ----------------------------------------------

echo "--- Generating Ephemeral Credentials ---"

# 1. Calculate the expiration timestamp (Current time + duration)
# This calculation works reliably on both Linux and macOS
EXPIRATION=$(( $(date +%s) + $DURATION ))

# 2. Construct the Username (format: <expiration>:<identifier>)
USERNAME="${EXPIRATION}:${IDENTIFIER}"

# 3. Generate the Password (HMAC-SHA1 hash of the username, keyed by the secret, then Base64 encoded)
# CRITICAL: 'echo -n' ensures no trailing newline is added to the username before hashing.
# Omitting -n is the most common cause of authentication failure with this mechanism.
PASSWORD=$(echo -n $USERNAME | openssl dgst -sha1 -hmac $SECRET -binary | base64)

# 4. Print the credentials
echo "--------------------------------------------------"
echo "Generated Username: $USERNAME"
echo "Generated Password: $PASSWORD"
# Optional: Print the start of the secret to verify which one is being used
# echo "Secret Used (start): ${SECRET:0:5}..."
echo "--------------------------------------------------"
echo ""

# 5. Invoke turnutils_uclient
echo "--- Invoking turnutils_uclient against $SERVER_IP ---"
# Flags used:
# -y: Use the server address as the remote peer address for the test loopback.
#     This allows the client to verify that the relay is functional by sending data through it back to itself.
# -v: Verbose output.
# -u: Username.
# -w: Password.

turnutils_uclient  -e 136.49.107.143 -v -u "$USERNAME" -w "$PASSWORD" $SERVER_IP
