#!/bin/bash

# Test authentication with hashed tokens

set -euo pipefail

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

# Cleanup function
function cleanup() {
    if [ -n "$SERVER_PID" ]; then
        echo ""
        echo "Cleaning up: Stopping server (PID: $SERVER_PID)..."
        kill $SERVER_PID 2>/dev/null || true
        wait $SERVER_PID 2>/dev/null || true
    fi
}

# Set up trap to ensure cleanup on exit
trap cleanup EXIT INT TERM

echo "Testing token authentication with bcrypt hashes..."

# Generate test configuration with hashed tokens
echo "1. Generating config with bcrypt-hashed tokens..."
source ${SCRIPT_DIR}/generate_test_config.sh

# Copy config to where server expects it
mkdir -p ~/.config/simple_object_storage/
cp ${SCRIPT_DIR}/sos_config.json ~/.config/simple_object_storage/sos_config.json

# Start server if not running
if ! curl -s http://127.0.0.1:7703/status > /dev/null 2>&1; then
    echo "2. Starting server..."
    ${PARENT_DIR}/output/simple-object-server > /tmp/server.log 2>&1 &
    SERVER_PID=$!
    sleep 2
fi

# Test with plaintext token (server has hashed version)
echo "3. Testing authentication with hashed tokens..."
RESPONSE=$(curl -s -X PUT \
    -H "Authorization: Bearer ${TEST_TOKEN1}" \
    -F "file=@${SCRIPT_DIR}/test.sh" \
    -F 'metadata={"labeltags":["test:auth1"]}' \
    "http://127.0.0.1:7703/upload")

if echo "$RESPONSE" | grep -q '"result":"success"'; then
    echo "✓ Token 1 authentication successful"
    HASH=$(echo "$RESPONSE" | jq -r '.hash')
    # Clean up
    curl -s -H "Authorization: Bearer ${TEST_TOKEN1}" \
        "http://127.0.0.1:7703/deleteobject?hash=${HASH}" > /dev/null
else
    echo "✗ Token 1 authentication failed: $RESPONSE"
fi

# Test with second token
echo "4. Testing with second token..."
RESPONSE=$(curl -s -X PUT \
    -H "Authorization: Bearer ${TEST_TOKEN2}" \
    -F "file=@${SCRIPT_DIR}/test.sh" \
    -F 'metadata={"labeltags":["test:auth2"]}' \
    "http://127.0.0.1:7703/upload")

if echo "$RESPONSE" | grep -q '"result":"success"'; then
    echo "✓ Token 2 authentication successful"
    HASH=$(echo "$RESPONSE" | jq -r '.hash')
    # Clean up
    curl -s -H "Authorization: Bearer ${TEST_TOKEN2}" \
        "http://127.0.0.1:7703/deleteobject?hash=${HASH}" > /dev/null
else
    echo "✗ Token 2 authentication failed: $RESPONSE"
fi

# Test with invalid token
echo "5. Testing with invalid token (should fail)..."
RESPONSE=$(curl -s -X PUT \
    -H "Authorization: Bearer invalid_token_12345" \
    -F "file=@${SCRIPT_DIR}/test.sh" \
    -F 'metadata={"labeltags":["test:auth3"]}' \
    "http://127.0.0.1:7703/upload")

if echo "$RESPONSE" | grep -q '"error"'; then
    echo "✓ Invalid token correctly rejected"
else
    echo "✗ Invalid token was incorrectly accepted: $RESPONSE"
fi

echo ""
echo "Authentication tests complete!"
# Cleanup will be handled by the trap