#!/bin/bash
# client_9p - 9P client tool wrapping ollie-9p
set -euo pipefail

# Read JSON args from stdin
args=$(cat)
op=$(echo "$args" | jq -r '.op // empty')
path=$(echo "$args" | jq -r '.path // empty')
data=$(echo "$args" | jq -r '.data // empty')

# Tool calls commonly use the session placeholders from the client_9p API.
# Expand them here because jq returns the path literally and ollie-9p does
# not perform shell expansion on arguments.
expand_path() {
    local value=$1
    if [[ "$value" == *'$OLLIE_SESSION_ID'* ]]; then
        if [[ -z "${OLLIE_SESSION_ID:-}" ]]; then
            echo "error: OLLIE_SESSION_ID is not set" >&2
            exit 1
        fi
        value=${value//\$OLLIE_SESSION_ID/$OLLIE_SESSION_ID}
    fi
    if [[ "$value" == *'$OLLIE_UNAME'* ]]; then
        if [[ -z "${OLLIE_UNAME:-}" ]]; then
            echo "error: OLLIE_UNAME is not set" >&2
            exit 1
        fi
        value=${value//\$OLLIE_UNAME/$OLLIE_UNAME}
    fi
    printf '%s' "$value"
}

path=$(expand_path "$path")

if [[ -z "$op" ]]; then
    echo "error: missing 'op' (read, write, rdwr)" >&2
    exit 1
fi
if [[ -z "$path" ]]; then
    echo "error: missing 'path'" >&2
    exit 1
fi

case "$op" in
    read)
        ollie-9p read "$path"
        ;;
    write)
        echo -n "$data" | ollie-9p write "$path"
        ;;
    rdwr)
        echo -n "$data" | ollie-9p rdwr "$path"
        ;;
    *)
        echo "error: unknown op '$op' (use read, write, rdwr)" >&2
        exit 1
        ;;
esac
