#!/bin/bash
# Shell — execute a single bash command in a sandboxed environment.
# Already running inside the sandbox applied by toolsrv.
# Reads JSON args from stdin: {"cmd": "...", "timeout": 30, "bypass": false}
#
# This is the bootstrap primitive. All other tool scripts use this
# to execute commands on the system.

set -euo pipefail

# Parse JSON args from stdin.
args=$(cat)

# Extract fields using python (preferred) or jq (fallback).
if command -v python3 &>/dev/null; then
  cmd=$(echo "$args" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('cmd',''))")
elif command -v python &>/dev/null; then
  cmd=$(echo "$args" | python -c "import json,sys; d=json.load(sys.stdin); print(d.get('cmd',''))")
elif command -v jq &>/dev/null; then
  cmd=$(echo "$args" | jq -r '.cmd // ""')
else
  echo '{"isError":true,"content":[{"type":"text","text":"shell: need python3, python, or jq to parse args"}]}'
  exit 1
fi

if [ -z "$cmd" ]; then
  echo '{"isError":true,"content":[{"type":"text","text":"shell: cmd is required"}]}'
  exit 1
fi

# Execute the command. The sandbox (landlock) is already applied by toolsrv.
# We use eval to handle pipes, redirects, and compound commands.
# Output streams directly to stdout/stderr for real-time capture.
# Run in a subshell so 'exit N' doesn't kill this script.
# Disable errexit for the subshell so we can capture the exit code.
set +e
(eval "$cmd") 2>&1
rc=$?
set -e
echo "exit: $rc"
exit $rc