#!/bin/bash

# Generate secure random tokens and create test configuration
# This script generates a new sos_config.json with random bcrypt-hashed tokens for each test run
# The plaintext tokens are exported as environment variables for use in tests

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
CONFIG_FILE="${SCRIPT_DIR}/sos_config.json"
PARENT_DIR=$(cd "${SCRIPT_DIR}/.." && pwd)

# Function to generate a secure random token
generate_token() {
    # Generate 32 bytes of random data and encode as base64
    # Remove non-alphanumeric characters for simplicity
    openssl rand -base64 32 | tr -d '/+=' | cut -c1-32
}

# Generate 3 random tokens
TOKEN1=$(generate_token)
TOKEN2=$(generate_token)
TOKEN3=$(generate_token)

# Export plaintext tokens as environment variables for scripts that need them
export TEST_TOKEN1="${TOKEN1}"
export TEST_TOKEN2="${TOKEN2}"
export TEST_TOKEN3="${TOKEN3}"

echo "Generating bcrypt-hashed tokens (this may take a moment)..."

# Check if hash_token utility exists
if [ ! -f "${PARENT_DIR}/output/hash_token" ]; then
    echo "Error: hash_token utility not found at ${PARENT_DIR}/output/hash_token"
    echo "Please build it first with: ./build.sh"
    exit 1
fi

# Generate bcrypt hashes with cost factor 10 (faster for testing)
HASH1=$("${PARENT_DIR}/output/hash_token" -c 10 -q "${TOKEN1}")
HASH2=$("${PARENT_DIR}/output/hash_token" -c 10 -q "${TOKEN2}")
HASH3=$("${PARENT_DIR}/output/hash_token" -c 10 -q "${TOKEN3}")

# Create configuration with hashed tokens
cat > "${CONFIG_FILE}" << EOF
{
    "write_tokens": [
        "${HASH1}",
        "${HASH2}",
        "${HASH3}"
    ],
    "rate_limiting": {
        "auth_rate_limit": 5,
        "auth_window_seconds": 2
    },
    "port": 7703,
    "host": "127.0.0.1"
}
EOF

echo "Generated test configuration with bcrypt-hashed tokens:"
echo "  Token 1 (plaintext): ${TOKEN1:0:8}... (hash: ${HASH1:0:20}...)"
echo "  Token 2 (plaintext): ${TOKEN2:0:8}... (hash: ${HASH2:0:20}...)"
echo "  Token 3 (plaintext): ${TOKEN3:0:8}... (hash: ${HASH3:0:20}...)"

echo "Configuration written to: ${CONFIG_FILE}"