#!/bin/bash
# Integration test for entrypoint.sh sanitization
# This simulates what happens when Portainer passes environment variables with Unicode characters

set -e

# Define Unicode character constants for testing
readonly U200E_HEX=$'\xE2\x80\x8E'  # U+200E Left-to-Right Mark
readonly U200B_HEX=$'\xE2\x80\x8B'  # U+200B Zero Width Space

echo "=========================================="
echo "Entrypoint.sh Sanitization Integration Test"
echo "=========================================="
echo ""

# Create a test directory
TEST_DIR=$(mktemp -d /tmp/entrypoint_test.XXXXXX)
cd "$TEST_DIR"

echo "Test 1: Simulating environment with invisible Unicode characters..."

# Create a script that exports variables with invisible Unicode characters
# This simulates what Portainer would do when env vars contain U+200E
cat > "${TEST_DIR}/set_env_with_unicode.sh" << 'EOF'
#!/bin/bash
# Simulate Portainer environment with invisible Unicode characters
export ADMIN_USER="testuser"
export ADMIN_PASSWORD="testpass"
export OPENROUTER_API_KEY="test-key-123"
EOF

# Add invisible U+200E character after variable names (simulating the Portainer bug)
printf "export TEST_VAR_U200E%s=\"value1\"\n" "$U200E_HEX" >> "${TEST_DIR}/set_env_with_unicode.sh"
printf "export TEST_VAR_U200B%s=\"value2\"\n" "$U200B_HEX" >> "${TEST_DIR}/set_env_with_unicode.sh"

echo "  Created test environment with Unicode characters"
echo ""

# Verify the test file has Unicode characters
echo "Test 2: Verifying test environment has invisible characters..."
if grep -q "$U200E_HEX" "${TEST_DIR}/set_env_with_unicode.sh" 2>/dev/null; then
    echo "  ✓ U+200E detected in test file"
else
    echo "  ✗ Failed to create test file with U+200E"
    exit 1
fi
echo ""

# Source the environment with Unicode characters
echo "Test 3: Loading environment with Unicode characters..."
source "${TEST_DIR}/set_env_with_unicode.sh" 2>/dev/null || true
echo "  Environment loaded"
echo ""

# Extract and test just the sanitization function from entrypoint.sh
echo "Test 4: Testing sanitization function..."
RESULT_FILE=$(mktemp /tmp/sanitized_result.XXXXXX)
cat > "${TEST_DIR}/test_sanitize.sh" << SANITIZE_EOF
#!/bin/bash
sanitize_env_vars() {
    echo "Sanitizing environment variables..."
    
    # Create a secure temporary file
    local temp_env
    temp_env=\$(mktemp /tmp/sanitized_env.XXXXXX)
    
    # Export current environment to a file, then clean it
    export -p > "\$temp_env"
    
    # Remove common invisible Unicode characters
    sed -i \\
        -e 's/\\xE2\\x80\\x8E//g' \\
        -e 's/\\xE2\\x80\\x8F//g' \\
        -e 's/\\xE2\\x80\\x8B//g' \\
        -e 's/\\xEF\\xBB\\xBF//g' \\
        -e 's/\\xE2\\x80\\xAA//g' \\
        -e 's/\\xE2\\x80\\xAB//g' \\
        -e 's/\\xE2\\x80\\xAC//g' \\
        -e 's/\\xE2\\x80\\xAD//g' \\
        -e 's/\\xE2\\x80\\xAE//g' \\
        "\$temp_env" 2>/dev/null
    
    # Source the sanitized environment
    if ! source "\$temp_env" 2>/dev/null; then
        echo "WARNING: Failed to source sanitized environment"
    fi
    
    # Clean up temporary file
    rm -f "\$temp_env"
    
    echo "Environment variables sanitized successfully"
}

# Run the sanitization
sanitize_env_vars

# Verify variables are still accessible after sanitization
echo ""
echo "Verifying sanitized environment variables:"
echo "  ADMIN_USER=\$ADMIN_USER"
echo "  ADMIN_PASSWORD=\$ADMIN_PASSWORD"
echo "  OPENROUTER_API_KEY=\$OPENROUTER_API_KEY"

# Export the sanitized environment for verification
export -p > "$RESULT_FILE"
SANITIZE_EOF

chmod +x "${TEST_DIR}/test_sanitize.sh"

# Run the sanitization test
bash "${TEST_DIR}/test_sanitize.sh"
echo ""

# Verify the sanitized output doesn't have Unicode characters
echo "Test 5: Verifying Unicode characters are removed after sanitization..."
if [ ! -f "$RESULT_FILE" ]; then
    echo "  ✗ FAILED: Could not find sanitized result file"
    exit 1
fi

if grep -q "$U200E_HEX" "$RESULT_FILE" 2>/dev/null; then
    echo "  ✗ FAILED: U+200E still present after sanitization"
    exit 1
else
    echo "  ✓ U+200E successfully removed"
fi

if grep -q "$U200B_HEX" "$RESULT_FILE" 2>/dev/null; then
    echo "  ✗ FAILED: U+200B still present after sanitization"
    exit 1
else
    echo "  ✓ U+200B successfully removed"
fi
echo ""

# Verify environment variables are preserved
echo "Test 6: Verifying environment variables are preserved..."
source "$RESULT_FILE"

if [ "$ADMIN_USER" = "testuser" ]; then
    echo "  ✓ ADMIN_USER preserved correctly"
else
    echo "  ✗ FAILED: ADMIN_USER=$ADMIN_USER (expected: testuser)"
    exit 1
fi

if [ "$ADMIN_PASSWORD" = "testpass" ]; then
    echo "  ✓ ADMIN_PASSWORD preserved correctly"
else
    echo "  ✗ FAILED: ADMIN_PASSWORD=$ADMIN_PASSWORD (expected: testpass)"
    exit 1
fi
echo ""

# Cleanup
rm -rf "$TEST_DIR"
rm -f "$RESULT_FILE"

echo "=========================================="
echo "All integration tests PASSED! ✓"
echo "=========================================="
echo ""
echo "The entrypoint.sh sanitization will automatically fix"
echo "the Portainer U+200E error on container startup."
