#!/usr/bin/env sh
# write-sidecar — refresh the skybox sidecar on every service start.
#
# Executed by opencode-agent.service as User=opencode-agent Group=agent-workspace,
# so the file lands opencode-agent:agent-workspace 0640 (umask 027) — readable
# by group members (the human account). No setgid, no ACLs.
#
# /run is tmpfs — the sidecar is (re)created per boot and on every start, so it
# is always in sync after a password rotation (systemctl stop -> regenerate
# /etc/opencode-agent/password -> systemctl start).

set -eu

: "${OPENCODE_SERVER_PASSWORD:?missing env - check /etc/opencode-agent/password}"

url=http://127.0.0.1:4096
# The mount root is disk-backed: a package directory under /var/lib, flushed at
# every boot by the tmpfiles.d `D` entry (opencode-skybox.conf). It is
# root:agent-workspace 0750 (mount targets are created by root, not by the
# agent) with traversal through the 0750 parent for the human and the agent.
# The agent's writable worktrees live in `coding/worktrees` (agent-owned). It
# cannot live under the agent's 0700 home: the human client must be able to
# chdir() into a mount.
projects_root=/var/lib/opencode-agent/coding

umask 027
mkdir -p "$projects_root"
printf '{"url":"%s","password":"%s","projects_root":"%s"}\n' \
    "$url" "$OPENCODE_SERVER_PASSWORD" "$projects_root" > /run/opencode-agent/server.json
