#!/bin/sh
set -eu
J=/tmp/hermes-workspace-auth-cookie.$$
O=/tmp/hermes-workspace-terminal.$$
trap 'rm -f "$J" "$O"' EXIT
python3 - <<'PY' | curl -sS -c "$J" -b "$J" -H 'Content-Type: application/json' --data-binary @- https://hermes-workspace.agentsolutions-mallorca.com/api/auth >/dev/null
import os, json
print(json.dumps({'password': os.environ.get('HERMES_PASSWORD') or os.environ.get('CLAUDE_PASSWORD')}))
PY
AUTH=$(curl -sS -b "$J" https://hermes-workspace.agentsolutions-mallorca.com/api/auth-check)
curl -sS -N -i --max-time 8 -b "$J" -H 'Content-Type: application/json' -X POST https://hermes-workspace.agentsolutions-mallorca.com/api/terminal-stream --data-binary '{"cwd":"~/.hermes","cols":80,"rows":24}' > "$O" || true
grep -E '^(HTTP/|content-type:|event: session|data: .*sessionId)' "$O" | head -10
echo "AUTH_CHECK=$AUTH"
SID=$(grep 'data: .*sessionId' "$O" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p' | head -1)
if [ -n "$SID" ]; then INPUT=$(curl -sS -b "$J" -H 'Content-Type: application/json' -X POST https://hermes-workspace.agentsolutions-mallorca.com/api/terminal-input --data-binary "{\"sessionId\":\"$SID\",\"data\":\"echo AUTH_TEST\\n\"}"); echo "TERMINAL_INPUT=$INPUT"; curl -sS -b "$J" -H 'Content-Type: application/json' -X POST https://hermes-workspace.agentsolutions-mallorca.com/api/terminal-close --data-binary "{\"sessionId\":\"$SID\"}" >/dev/null; echo SESSION_CLOSED=YES; else echo SESSION_CLOSED=NO; fi