#!/bin/bash set -e # Check if jq is installed if ! command -v jq &> /dev/null; then echo "Error: jq is required but not installed." echo "Install it with: sudo apt-get install jq" exit 1 fi # Function to print usage usage() { echo "Usage: $0 " echo " $0 'json_string'" exit 1 } # Check if argument is provided if [ $# -ne 1 ]; then usage fi JSON="" # Process and clean up JSON input to handle any whitespace or formatting issues process_json() { local input="$1" # Use 'tr' to remove any trailing whitespace and control characters # Then use jq to validate and normalize the JSON structure echo "$input" | tr -d '\r' | sed 's/[[:space:]]*$//' | jq -c '.' } # Check if the argument is a file or a JSON string if [ -f "$1" ]; then # Validate JSON file if ! jq . "$1" > /dev/null 2>&1; then echo "Error: Invalid JSON in file $1" exit 1 fi # Read file content and process it FILE_CONTENT=$(cat "$1") JSON=$(process_json "$FILE_CONTENT") else # Check if it's a valid JSON string if ! echo "$1" | jq . > /dev/null 2>&1; then echo "Error: Invalid JSON string" exit 1 fi # Process the JSON string JSON=$(process_json "$1") fi # Double-check that we have valid JSON (defensive programming) if ! echo "$JSON" | jq . > /dev/null 2>&1; then echo "Error: Something went wrong processing the JSON" exit 1 fi # Base64 encode the JSON, ensuring no trailing newlines BASE64=$(echo -n "$JSON" | base64 | tr -d '\n') # Ensure the binary exists if [ ! -f "build/runner" ]; then echo "Building the project first..." ./build.sh fi # Run the command echo "Running command with JSON:" echo "$JSON" | jq . echo echo "Base64 encoded: $BASE64" echo # Execute the runner with the processed base64 input build/runner "$BASE64" EXIT_CODE=$? echo echo "Command exited with code: $EXIT_CODE" exit $EXIT_CODE