# Serve opencode for remote/browser attachment using repo-local .env secrets.
[positional-arguments]
opencode-serve *args:
    #!/usr/bin/env bash
    set -euo pipefail
    repo='{{justfile_directory()}}'
    if [ -f "$repo/.env" ]; then set -a; . "$repo/.env"; set +a; fi
    if [ -z "${OPENCODE_SERVER_PASSWORD:-}" ]; then
        printf '%s\n' 'Missing OPENCODE_SERVER_PASSWORD in .env' >&2
        exit 1
    fi
    export OPENCODE_SERVER_PASSWORD
    hostname="${TRAPOS_OPENCODE_HOSTNAME:-0.0.0.0}"
    port="${TRAPOS_OPENCODE_PORT:-4242}"
    exec opencode serve --hostname "$hostname" --port "$port" "$@"

# Attach to the local opencode server. Pass a URL first to override the default.
[positional-arguments]
opencode-attach *args:
    #!/usr/bin/env bash
    set -euo pipefail
    repo='{{justfile_directory()}}'
    if [ -f "$repo/.env" ]; then set -a; . "$repo/.env"; set +a; fi
    if [ -z "${OPENCODE_SERVER_PASSWORD:-}" ]; then
        printf '%s\n' 'Missing OPENCODE_SERVER_PASSWORD in .env' >&2
        exit 1
    fi
    export OPENCODE_SERVER_PASSWORD
    port="${TRAPOS_OPENCODE_PORT:-4242}"
    target="http://127.0.0.1:$port"
    if [ "${1:-}" != "" ]; then
        case "$1" in http://*|https://*) target="$1"; shift ;; esac
    fi
    exec opencode attach "$target" "$@"
