package guesttools import ( "bytes" "fmt" "io" "os" "path/filepath" "github.com/Nwflower/reims-go/internal/installer" ) const ( ToolsVolumeName = "REIMSTOOLS" InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command" ) // BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS") // containing the per-VM Bearer token config, POSIX guest agent script (two-way // clipboard + ReimsShare folder sync), and one-click install/uninstall commands. func BuildToolsDiskImage(outPath string, cfg VMConfig) error { if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { return err } confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL=\"http://10.0.2.2:%d\"\nREIMS_TOKEN=\"%s\"\nREIMS_VM=\"%s\"\n", cfg.Port, cfg.Token, cfg.VMName)) agentBytes := GuestAgentScript() installBytes := GuestInstallScript() uninstallBytes := GuestUninstallScript() files := []installer.HFSFile{ { Name: "config", Mode: 0o100644, Size: int64(len(confBytes)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(confBytes)), nil }, }, { Name: "guest-tools.sh", Mode: 0o100755, Size: int64(len(agentBytes)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(agentBytes)), nil }, }, { Name: "Install-Reims-Tools.command", Mode: 0o100755, Size: int64(len(installBytes)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(installBytes)), nil }, }, { Name: "Uninstall-Reims-Tools.command", Mode: 0o100755, Size: int64(len(uninstallBytes)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(uninstallBytes)), nil }, }, } return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) } // GuestAgentScript returns the stock-macOS POSIX shell daemon (no Xcode or // Python required) that syncs UTF-8 clipboard text every 1s and ~/ReimsShare // files every 3s over the token-authenticated host bridge. func GuestAgentScript() []byte { return []byte(`#!/bin/sh # Reims Guest Tools: token-authenticated two-way clipboard & ReimsShare sync. set -u APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" CONF="$APP_DIR/config" SHARE="$HOME/ReimsShare" TMP_DIR="$APP_DIR/tmp" mkdir -p "$APP_DIR" "$SHARE" "$TMP_DIR" [ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true load_conf() { if [ -f "/Volumes/REIMSTOOLS/config" ]; then cp "/Volumes/REIMSTOOLS/config" "$CONF" 2>/dev/null || true chmod 600 "$CONF" 2>/dev/null || true fi if [ -f "$CONF" ]; then # shellcheck disable=SC1090 . "$CONF" fi } REIMS_HOST_URL="" REIMS_TOKEN="" load_conf urlencode() { # Percent-encodes UTF-8 paths cleanly with stock macOS tools (LC_ALL=C awk). LC_ALL=C awk 'BEGIN { for (i = 0; i < 256; i++) ord[sprintf("%c", i)] = i s = ARGV[1] out = "" for (i = 1; i <= length(s); i++) { c = substr(s, i, 1) if (c ~ /[A-Za-z0-9._~\/-]/) out = out c else out = out sprintf("%%%02X", ord[c]) } printf "%s", out }' "$1" } hash_file() { shasum -a 256 "$1" 2>/dev/null | awk '{print $1}' } last_clip_hash="" tick=0 TAB=$(printf '\t') sync_clipboard() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 clip_in="$TMP_DIR/clip_in" clip_out="$TMP_DIR/clip_out" hdr_out="$TMP_DIR/clip_hdr" pbpaste >"$clip_in" 2>/dev/null || : >"$clip_in" cur_hash=$(hash_file "$clip_in") if [ -n "$last_clip_hash" ] && [ "$cur_hash" != "$last_clip_hash" ]; then if curl -fsS -m 3 -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: text/plain; charset=utf-8" \ --data-binary "@$clip_in" \ "$REIMS_HOST_URL/v1/clipboard" >/dev/null 2>&1; then last_clip_hash="$cur_hash" fi return 0 fi code=$(curl -sS -m 3 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \ -H "Authorization: Bearer $REIMS_TOKEN" \ "$REIMS_HOST_URL/v1/clipboard?since=$last_clip_hash" 2>/dev/null || echo "000") if [ "$code" = "200" ]; then new_hash=$(awk 'tolower($1)=="x-clip-hash:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out") if [ -n "$new_hash" ] && [ "$new_hash" != "$cur_hash" ]; then pbcopy <"$clip_out" 2>/dev/null || true last_clip_hash="$new_hash" elif [ -n "$new_hash" ]; then last_clip_hash="$new_hash" fi elif [ "$code" = "304" ] && [ -z "$last_clip_hash" ]; then last_clip_hash="$cur_hash" fi } sync_files() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 remote_list="$TMP_DIR/remote_files.tsv" if ! curl -fsS -m 5 \ -H "Authorization: Bearer $REIMS_TOKEN" \ "$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then return 0 fi # 1. Host -> Guest (download new or strictly newer files) while IFS="$TAB" read -r rmtime rsize rrel; do [ -n "$rrel" ] || continue local_path="$SHARE/$rrel" need_dl=0 if [ ! -f "$local_path" ]; then need_dl=1 else lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0) if [ "$rmtime" -gt $((lmtime + 2)) ]; then need_dl=1 fi fi if [ "$need_dl" -eq 1 ]; then mkdir -p "$(dirname "$local_path")" enc=$(urlencode "$rrel") dl_tmp="$TMP_DIR/dl.part" if curl -fsS -m 60 \ -H "Authorization: Bearer $REIMS_TOKEN" \ "$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then mv -f "$dl_tmp" "$local_path" touch -d "@$rmtime" "$local_path" 2>/dev/null || true else rm -f "$dl_tmp" fi fi done <"$remote_list" # 2. Guest -> Host (upload new or strictly newer files) find "$SHARE" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do rel=${fpath#"$SHARE/"} [ -n "$rel" ] || continue lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0) lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0) [ "$lsize" -le 268435456 ] || continue rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list") [ -n "$rmtime" ] || rmtime=0 if [ "$lmtime" -gt $((rmtime + 2)) ]; then enc=$(urlencode "$rel") curl -fsS -m 60 -X PUT \ -H "Authorization: Bearer $REIMS_TOKEN" \ --data-binary "@$fpath" \ "$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true fi done } while :; do if [ $((tick % 10)) -eq 0 ]; then load_conf fi sync_clipboard if [ $((tick % 3)) -eq 0 ]; then sync_files fi tick=$((tick + 1)) sleep 1 done `) } // GuestInstallScript returns the double-clickable / one-command installer script // placed on /Volumes/REIMSTOOLS. func GuestInstallScript() []byte { return []byte(`#!/bin/sh set -e SRC="/Volumes/REIMSTOOLS" APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist" SHARE="$HOME/ReimsShare" if [ ! -f "$SRC/config" ] || [ ! -f "$SRC/guest-tools.sh" ]; then echo "REIMSTOOLS volume not found at $SRC" >&2 exit 1 fi mkdir -p "$APP_DIR" "$HOME/Library/LaunchAgents" "$SHARE" cp "$SRC/config" "$APP_DIR/config" cp "$SRC/guest-tools.sh" "$APP_DIR/guest-tools.sh" chmod 600 "$APP_DIR/config" chmod 755 "$APP_DIR/guest-tools.sh" [ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true cat >"$PLIST" < Label com.reimsgo.guest-tools ProgramArguments /bin/sh $APP_DIR/guest-tools.sh RunAtLoad KeepAlive StandardOutPath $APP_DIR/agent.log StandardErrorPath $APP_DIR/agent.log EOF uid=$(id -u) launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST" # Verify host bridge connectivity immediately. . "$APP_DIR/config" if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then echo "Reims Guest Tools installed and connected!" echo "Shared folder: ~/Desktop/ReimsShare (synced with Windows host)" else echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." fi `) } // GuestUninstallScript cleanly removes the LaunchAgent while preserving user files. func GuestUninstallScript() []byte { return []byte(`#!/bin/sh set -e APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist" uid=$(id -u) launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true rm -f "$PLIST" rm -rf "$APP_DIR" echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept." `) }