#!/bin/bash
OC_INSTALL_DIR="/usr/lib/openclaw"
export PATH="$OC_INSTALL_DIR/runtime/node/bin:$PATH"
export OPENCLAW_GATEWAY_PORT="${OPENCLAW_GATEWAY_PORT:-18789}"
export ELECTRON_DISABLE_SANDBOX=1
export ELECTRON_ENABLE_LOGGING=1

LOG="/tmp/openclaw-desktop.log"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting OpenClaw Desktop..." > "$LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] DISPLAY=$DISPLAY USER=$(whoami) HOME=$HOME" >> "$LOG"

if [ ! -x "$OC_INSTALL_DIR/client/electron" ]; then
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: electron not found" >> "$LOG"
  exit 1
fi

"$OC_INSTALL_DIR/client/electron" \
  --no-sandbox \
  --disable-gpu-sandbox \
  --disable-gpu \
  --disable-software-rasterizer \
  --disable-dev-shm-usage \
  "$OC_INSTALL_DIR/client" \
  >> "$LOG" 2>&1

RC=$?
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Electron exited code=$RC" >> "$LOG"

if [ $RC -ne 0 ]; then
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] Retrying with fallback flags..." >> "$LOG"
  "$OC_INSTALL_DIR/client/electron" \
    --no-sandbox \
    --disable-gpu \
    --disable-gpu-compositing \
    --disable-software-rasterizer \
    --disable-dev-shm-usage \
    --in-process-gpu \
    "$OC_INSTALL_DIR/client" \
    >> "$LOG" 2>&1
fi
