#!/usr/bin/env bash
# bash -c "$(wget -qLO- https://github.com/therepos/proxmox/raw/main/apps/setup-claudeubuntu.sh?$(date +%s))"
# Purpose: Installs Claude Code (Remote Control boot service) and Claude Desktop in the browser via KasmVNC (Ubuntu VM)
# =============================================================================
# Usage:
#   Run inside the Ubuntu VM (not the PVE host), as root or via sudo, from a
#   console where you can type (Proxmox console or SSH). Menu:
#     1) Install     Claude Code (login, Remote Control boot service) and
#                    Claude Desktop on XFCE, streamed to any browser by KasmVNC,
#                    so the app's Chat can use folders on this VM from anywhere
#     2) Status      services, versions, working folder, streaming mode
#     3) Update      update Claude Code and Claude Desktop
#     4) Settings    1) Improve stream performance  2) Improve stream quality
#                    3) Balance stream (work networks: sharper scrolling)
#                    (browser desktop: 30 fps / panel ignored, or KasmVNC defaults)
#                    4) Fix VM IP (netplan static address, auto-reverts if broken)
#     5) Connectors  1) Connect GitHub (so Claude Code here can read and push your
#                    repos, like claude.ai)  2) Disconnect GitHub
#     6) Logs        latest Remote Control and desktop log lines
#     7) Uninstall   remove the desktop and the service (optionally Claude Code)
#   Args skip the menu: install | status | update | settings [performance|balanced|quality|ip]
#                       | connectors [github|github-off] | logs | uninstall
#
#   After install: Claude app -> Code tab -> tap this VM under Devices.
#   Watch the live session:   tmux attach -t claude   (detach: Ctrl+B then D)
#   Desktop: open https://<host-ip>:8444, sign in to the app, then
#   project -> Add folder -> the working folder. claude-rc keeps running alongside.
#
# Bookmark URL (JPEG/WebP, for a weak laptop):
#   https://<host-ip>:8444/?kasmvnc_mode_preference=image
#
# Config (env): CLAUDE_USER, CLAUDE_WORKDIR, CLAUDE_RC_NAME, CLAUDE_DESKTOP_PORT
# =============================================================================

set -euo pipefail

# --- Variables ---------------------------------------------------------------
SERVICE_NAME="claude-rc"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
CONF_FILE="/etc/claude-rc.conf"
TMUX_SESSION="claude"
DEFAULT_WORKDIR="/mnt/sec/media/shared"
INSTALL_URL="https://claude.ai/install.sh"
# Desktop bridge (Claude Desktop for Linux, Anthropic apt repo)
DESKTOP_KEY_URL="https://downloads.claude.ai/claude-desktop/key.asc"
DESKTOP_KEY_FILE="/usr/share/keyrings/claude-desktop-archive-keyring.asc"
DESKTOP_KEY_FPR="31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE"
DESKTOP_REPO_FILE="/etc/apt/sources.list.d/claude-desktop.list"
DESKTOP_REPO_LINE="deb [arch=amd64,arm64 signed-by=${DESKTOP_KEY_FILE}] https://downloads.claude.ai/claude-desktop/apt/stable stable main"
# Browser for links the app opens (Mozilla apt repo; the snap cannot run in the desktop service)
BROWSER_KEY_URL="https://packages.mozilla.org/apt/repo-signing-key.gpg"
BROWSER_KEY_FILE="/etc/apt/keyrings/packages.mozilla.org.asc"
BROWSER_KEY_FPR="35BAA0B33E9EB396F59CA838C0BA5CE6DC6315A3"
BROWSER_REPO_FILE="/etc/apt/sources.list.d/mozilla.list"
BROWSER_REPO_LINE="deb [signed-by=${BROWSER_KEY_FILE}] https://packages.mozilla.org/apt mozilla main"
BROWSER_PIN_FILE="/etc/apt/preferences.d/mozilla"
DESKTOP_SERVICE="claude-desktop"
DESKTOP_SERVICE_FILE="/etc/systemd/system/${DESKTOP_SERVICE}.service"
DESKTOP_DISPLAY=":1"
DESKTOP_PORT="${CLAUDE_DESKTOP_PORT:-8444}"
AUTOLOGIN_FILE="/etc/lightdm/lightdm.conf.d/50-autologin.conf"   # older versions only
SLEEP_TARGETS="sleep.target suspend.target hibernate.target hybrid-sleep.target"
DESKTOP_PKGS="xfce4 xfce4-terminal dbus-x11 gnome-keyring ssl-cert"
# Streaming modes for the browser desktop (menu: Settings):
#   performance  for Cloudflare Tunnel, office proxies, any slow link: 30 fps,
#                picture quality 3-6, the server ignores the browser's settings
#                panel. Default.
#   quality      for LAN or a fast link: KasmVNC's own values (60 fps,
#                quality 5-6, panel allowed).
#   balanced     for a workplace browser where Performance looks blocky: 30 fps,
#                quality 5-7, panel ignored, scroll detection off (smooth
#                scrolling in the Claude app rarely matches whole-line moves).
STREAM_DEFAULT="performance"
stream_label() {
    case "${1:-}" in
        quality)  echo "Quality" ;;
        balanced) echo "Balanced" ;;
        *)        echo "Performance" ;;
    esac
}

# --- Helpers -----------------------------------------------------------------
# >>> admonition
if [[ -n "${FORCE_COLOR:-}" || -t 1 ]]; then
  _CK=$'\033[1;32m'; _CI=$'\033[1;36m'; _CW=$'\033[1;33m'; _CE=$'\033[1;31m'; _C0=$'\033[0m'
else
  _CK=''; _CI=''; _CW=''; _CE=''; _C0=''
fi
ok()   { printf '%s[ OK ]%s %s\n' "$_CK" "$_C0" "$*"; }
info() { printf '%s[INFO]%s %s\n' "$_CI" "$_C0" "$*"; }
warn() { printf '%s[WARN]%s %s\n' "$_CW" "$_C0" "$*" >&2; }
fail() { printf '%s[FAIL]%s %s\n' "$_CE" "$_C0" "$*" >&2; exit 1; }
banner() { local l='================================================='; printf '\n%s\n  %s\n%s\n' "$l" "$*" "$l"; }
# Status line: value red when missing/failed, yellow while starting, green when OK.
row() {
  local c=''
  case "${2,,}" in
    not|*"not "*|*not-*|*missing*|*fail*|*error*|*inactive*|*disconnected*) c="$_CE" ;;
    *activating*|*reconnecting*|*starting*) c="$_CW" ;;
    *installed*|*active*|*connected*|*"logged in"*|*running*|*enabled*|*mounted*|*loaded*) c="$_CK" ;;
  esac
  printf '  %-16s%s%s%s\n' "$1" "$c" "$2" "${c:+$_C0}"
}
# <<< admonition
# >>> menu
menu() {
  local o name desc i=1 w=0 pick
  { true </dev/tty; } 2>/dev/null || { warn "No terminal for the menu."; exit 0; }
  for o in "$@"; do name="${o%%|*}"; (( ${#name} > w )) && w=${#name}; done
  echo ""
  for o in "$@"; do
    name="${o%%|*}"; desc=""; [[ "$o" == *"|"* ]] && desc="${o#*|}"
    if [[ -n "$desc" ]]; then printf '  %d) %-*s  %s\n' "$i" "$w" "$name" "$desc"
    else printf '  %d) %s\n' "$i" "$name"; fi
    i=$((i + 1))
  done
  echo "  0) Exit"
  echo ""
  while true; do
    read -rp "  Choose [0-$#]: " pick </dev/tty || exit 0
    [[ "$pick" == "0" ]] && exit 0
    if [[ "$pick" =~ ^[0-9]+$ ]] && (( pick >= 1 && pick <= $# )); then
      CHOICE="${!pick}"; CHOICE="${CHOICE%%|*}"; return 0
    fi
    warn "Choose a number from 0 to $#."
  done
}
# <<< menu

[[ $EUID -eq 0 ]] || fail "This script must be run as root (or via sudo)."
[[ -d /etc/pve ]] && fail "This is the Proxmox host. Run this inside the Ubuntu VM instead."
[[ -r /dev/tty ]] || fail "No terminal available. Run from the VM console or SSH."

# ask "Prompt" "default" -> echoes the answer (default when empty)
ask() {
    local p="$1" def="${2:-}" in
    if [[ -n "$def" ]]; then
        read -rp "  $p [$def]: " in </dev/tty || in=""
    else
        read -rp "  $p: " in </dev/tty || in=""
    fi
    echo "${in:-$def}"
}

# confirm "Question" "Y|N" -> 0 for yes
confirm() {
    local q="$1" def="${2:-N}" in hint="[y/N]"
    [[ "$def" == "Y" ]] && hint="[Y/n]"
    read -rp "  $q $hint: " in </dev/tty || in=""
    in="${in:-$def}"
    [[ "$in" =~ ^[Yy]$ ]]
}

# Load settings so status/update/uninstall reuse them. Order: the saved config
# (written by Install), else values read back from an existing service file
# (a setup done by hand), else nothing. SETTINGS_SRC records which one won.
load_conf() {
    SETTINGS_SRC="none"
    if [[ -f "$CONF_FILE" ]]; then
        # shellcheck disable=SC1090
        source "$CONF_FILE"
        SETTINGS_SRC="$CONF_FILE"
    elif [[ -f "$SERVICE_FILE" ]]; then
        CLAUDE_USER="$(awk -F= '/^User=/{print $2; exit}' "$SERVICE_FILE")"
        CLAUDE_WORKDIR="$(awk -F= '/^WorkingDirectory=/{print $2; exit}' "$SERVICE_FILE")"
        CLAUDE_RC_NAME="$(grep -o -- '--name [^ '\'']*' "$SERVICE_FILE" | head -1 | cut -d' ' -f2)"
        SETTINGS_SRC="existing service (no ${CONF_FILE})"
    fi
    return 0
}

# Remote Control state, read from the live tmux screen of the service.
# Echoes: connected | not-connected | not-running
rc_state() {
    local u="$1" pane last
    as_user "$u" tmux has-session -t "$TMUX_SESSION" 2>/dev/null || { echo "not-running"; return; }
    pane="$(as_user "$u" tmux capture-pane -p -t "$TMUX_SESSION" -S -300 2>/dev/null || true)"
    last="$(grep -iE 'connected|reconnecting|failed|error|log ?in' <<<"$pane" | tail -1)"
    if grep -qiE '(^|[^a-z])connected' <<<"$last" && ! grep -qiE 'not connected|disconnected|failed' <<<"$last"; then
        echo "connected"
    else
        echo "not-connected"
    fi
}

user_home()  { getent passwd "$1" | cut -d: -f6; }
claude_bin() { echo "$(user_home "$1")/.local/bin/claude"; }

# Run a command as the target user with their HOME and PATH.
as_user() {
    local u="$1"; shift
    sudo -H -u "$u" env PATH="$(user_home "$u")/.local/bin:/usr/local/bin:/usr/bin:/bin" "$@"
}

# --- Settings ----------------------------------------------------------------
pick_settings() {
    load_conf
    local def_user="${CLAUDE_USER:-${SUDO_USER:-}}"
    [[ -z "$def_user" || "$def_user" == "root" ]] && \
        def_user="$(getent passwd 1000 | cut -d: -f1)"

    echo ""
    info "Claude runs as a normal user (not root). It works inside one folder."
    CLAUDE_USER="$(ask "Run as user" "$def_user")"
    id "$CLAUDE_USER" &>/dev/null || fail "User '$CLAUDE_USER' does not exist."
    [[ "$CLAUDE_USER" != "root" ]] || fail "Pick a normal user, not root."

    CLAUDE_WORKDIR="$(ask "Working folder" "${CLAUDE_WORKDIR:-$DEFAULT_WORKDIR}")"
    [[ -d "$CLAUDE_WORKDIR" ]] || fail "Folder '$CLAUDE_WORKDIR' not found. Mount the share first (setup-virtiofs.sh)."
    as_user "$CLAUDE_USER" test -w "$CLAUDE_WORKDIR" || \
        warn "User '$CLAUDE_USER' cannot write to $CLAUDE_WORKDIR. Claude will be read-only there."

    CLAUDE_RC_NAME="$(ask "Session name shown in the Claude app" "${CLAUDE_RC_NAME:-Server}")"
    [[ "$CLAUDE_RC_NAME" =~ ^[A-Za-z0-9._-]+$ ]] || fail "Use letters, digits, dot, dash or underscore only."

    save_conf
    ok "Settings saved to ${CONF_FILE}."
}

save_conf() {
    cat > "$CONF_FILE" <<EOF
CLAUDE_USER="${CLAUDE_USER}"
CLAUDE_WORKDIR="${CLAUDE_WORKDIR}"
CLAUDE_RC_NAME="${CLAUDE_RC_NAME}"
CLAUDE_STREAM="${CLAUDE_STREAM:-$STREAM_DEFAULT}"
EOF
    chmod 644 "$CONF_FILE"
}

# --- Install -----------------------------------------------------------------
install_packages() {
    info "Installing tmux and curl..."
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    apt-get install -y -qq tmux curl >/dev/null
    ok "tmux and curl installed."
}

install_claude() {
    local bin; bin="$(claude_bin "$CLAUDE_USER")"
    if [[ -x "$bin" ]]; then
        ok "Claude Code already installed ($(as_user "$CLAUDE_USER" "$bin" --version 2>/dev/null | head -1))."
        return 0
    fi
    info "Installing Claude Code for '${CLAUDE_USER}' (no progress shown, please wait)..."
    as_user "$CLAUDE_USER" bash -c "curl -fsSL ${INSTALL_URL} | bash" >/dev/null 2>&1 \
        || fail "Claude Code install failed. Check internet access from the VM."
    [[ -x "$bin" ]] || fail "Install finished but $bin is missing."
    ok "Claude Code installed ($(as_user "$CLAUDE_USER" "$bin" --version 2>/dev/null | head -1))."
}

# Login and the two one-time questions (trust folder, enable Remote Control)
# need a human, so this step runs Remote Control once in the foreground.
first_run() {
    local bin home; bin="$(claude_bin "$CLAUDE_USER")"; home="$(user_home "$CLAUDE_USER")"

    if [[ -f "${home}/.claude/.credentials.json" ]] && \
       ! confirm "Already logged in. Log in again?" "N"; then
        ok "Using the existing login."
    else
        echo ""
        info "Log in with your Claude account (Pro/Max). Choose the claude.ai option."
        info "The VM has no browser: open the link it shows on your phone or laptop,"
        info "sign in, then paste the code back here."
        echo ""
        as_user "$CLAUDE_USER" "$bin" auth login </dev/tty || fail "Login failed. Re-run Install to try again."
        ok "Logged in."
    fi

    echo ""
    info "One-time check: Remote Control starts in the foreground now."
    info "  - If asked 'Trust ${CLAUDE_WORKDIR}?' answer y"
    info "  - If asked 'Enable Remote Control?' answer y"
    info "  - When it shows 'Connected', press Ctrl+C. Setup then continues."
    echo ""
    confirm "Ready?" "Y" || fail "Cancelled."

    # A running service already serves the folder and the check would refuse
    # to start; stop it for now. write_service starts it again afterwards.
    if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
        info "Stopping the running '${SERVICE_NAME}' service for the check..."
        systemctl stop "$SERVICE_NAME" 2>/dev/null || true
    fi
    as_user "$CLAUDE_USER" tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true

    # Let Ctrl+C stop only the child, not this script.
    trap ':' INT
    (cd "$CLAUDE_WORKDIR" && as_user "$CLAUDE_USER" "$bin" remote-control --name "$CLAUDE_RC_NAME" </dev/tty) || true
    trap - INT
    echo ""
    ok "One-time check done."
}

write_service() {
    local home tmux_bin; home="$(user_home "$CLAUDE_USER")"
    tmux_bin="$(command -v tmux)" || fail "tmux not found."

    # Wait for the shared folder only if it lives on a separate mount.
    local mount_dep=""
    local mnt; mnt="$(findmnt -n -o TARGET --target "$CLAUDE_WORKDIR" 2>/dev/null || true)"
    [[ -n "$mnt" && "$mnt" != "/" ]] && mount_dep="RequiresMountsFor=${mnt}"

    cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Claude Code Remote Control
After=network-online.target
Wants=network-online.target
${mount_dep}

[Service]
Type=forking
User=${CLAUDE_USER}
Environment=HOME=${home}
Environment=PATH=${home}/.local/bin:/usr/local/bin:/usr/bin:/bin
WorkingDirectory=${CLAUDE_WORKDIR}
ExecStart=${tmux_bin} new-session -d -s ${TMUX_SESSION} -c ${CLAUDE_WORKDIR} 'claude remote-control --name ${CLAUDE_RC_NAME}; tmux capture-pane -p -S -40 | grep . | logger -t ${SERVICE_NAME}'
ExecStop=-${tmux_bin} kill-session -t ${TMUX_SESSION}
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target
EOF

    # A leftover manual session would block the service from starting.
    as_user "$CLAUDE_USER" "$tmux_bin" kill-session -t "$TMUX_SESSION" 2>/dev/null || true

    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME" >/dev/null 2>&1
    systemctl restart "$SERVICE_NAME"
    sleep 5
    systemctl is-active --quiet "$SERVICE_NAME" \
        || fail "Service failed to start. Run this again and choose Logs to see why."
    ok "Boot service '${SERVICE_NAME}' enabled and running."
}

# Unattended steps first (packages take minutes), then the two steps that need
# a human (Claude login, browser password), then the services.
do_install() {
    banner "Claude Code + Claude Desktop - Install"
    pick_settings
    install_packages
    install_claude
    install_desktop
    first_run
    write_service
    set_kasm_password
    write_kasm_config
    print_done
}

print_done() {
    banner "Install Complete"
    echo ""
    echo "  Claude Code"
    echo "  Use it        Claude app -> Code tab -> tap '$(hostname)' under Devices"
    echo "                or https://claude.ai/code in any browser"
    echo "  Folder        ${CLAUDE_WORKDIR}"
    echo "  Live view     sudo -u ${CLAUDE_USER} tmux attach -t ${TMUX_SESSION}"
    echo "                (detach with Ctrl+B then D, never Ctrl+C)"
    echo "  Restart       sudo systemctl restart ${SERVICE_NAME}"
    echo ""
    echo "  Claude Desktop (browser)"
    echo "  Open          https://$(hostname -I 2>/dev/null | awk '{print $1}'):${DESKTOP_PORT}"
    echo "                (self-signed certificate: accept the browser warning)"
    echo "  Login         ${CLAUDE_USER} + the browser password you set"
    echo "  Remote        Cloudflare tunnel -> https://<host-ip>:${DESKTOP_PORT} with No TLS Verify,"
    echo "                behind Cloudflare Access"
    echo "  Keyring       if asked for a new keyring password, leave it BLANK"
    echo "  Streaming     $(stream_label "${CLAUDE_STREAM:-$STREAM_DEFAULT}") mode; change it under 4) Settings"
    echo "  Restart       sudo systemctl restart ${DESKTOP_SERVICE}"
    echo ""
    echo "  Both start automatically on every boot."
    echo ""
}

# --- Status ------------------------------------------------------------------
do_status() {
    load_conf
    # No saved settings and no service: still check the usual user for an install.
    local u="${CLAUDE_USER:-}"
    if [[ -z "$u" ]]; then
        u="${SUDO_USER:-}"
        [[ -z "$u" || "$u" == "root" ]] && u="$(getent passwd 1000 | cut -d: -f1)"
    fi

    local bin="" ver="not installed" login="-" svc rc rc_txt tmux_txt gh_txt="-"
    if [[ -n "$u" ]]; then
        bin="$(claude_bin "$u")"
        if [[ -x "$bin" ]]; then
            ver="installed ($(as_user "$u" "$bin" --version 2>/dev/null | awk '{print $1; exit}'))  ${bin}"
            [[ -f "$(user_home "$u")/.claude/.credentials.json" ]] && login="logged in" || login="NOT logged in"
        fi
    fi
    tmux_txt="$(command -v tmux >/dev/null && echo installed || echo 'not installed')"
    [[ -n "$u" ]] && gh_txt="$(gh_state "$u")"

    if [[ -f "$SERVICE_FILE" ]]; then
        local act ena
        act="$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || true)"
        ena="$(systemctl is-enabled "$SERVICE_NAME" 2>/dev/null || true)"
        svc="${SERVICE_NAME}  ${act:-unknown} / ${ena:-unknown}"
        [[ "$ena" == "enabled" ]] && svc+=" (starts on boot)"
    else
        svc="not set up"
    fi

    rc="$( [[ -n "$u" ]] && command -v tmux >/dev/null && rc_state "$u" || echo not-running )"
    case "$rc" in
        connected)     rc_txt="Connected  (name: ${CLAUDE_RC_NAME:-?})" ;;
        not-connected) rc_txt="Running, NOT connected  -> attach to see why, or re-run Install to log in" ;;
        *)             rc_txt="Not running"
                       if [[ "${act:-}" == activating || "${act:-}" == failed ]]; then
                           rc_txt+="  -> it quits at start; choose Logs to see why"
                       fi ;;
    esac

    banner "Status"
    row "Claude Code"    "$ver"
    row "Login"          "$login"
    row "GitHub"         "$gh_txt"
    row "tmux"           "$tmux_txt"
    row "Service"        "$svc"
    row "Remote Control" "$rc_txt"
    row "Desktop"        "$(desktop_state "$u")"
    row "Streaming"      "$( [[ -f "$DESKTOP_SERVICE_FILE" ]] && stream_label "${CLAUDE_STREAM:-$STREAM_DEFAULT}" || echo - )"
    row "User"           "${u:--}"
    row "Folder"         "${CLAUDE_WORKDIR:--}"
    row "LAN IP"         "$(hostname -I 2>/dev/null | awk '{print $1}')"
    banner "Settings        ${SETTINGS_SRC}"
    echo ""
}

# --- Update ------------------------------------------------------------------
do_update() {
    load_conf
    [[ -n "${CLAUDE_USER:-}" ]] || fail "Not installed. Run Install first."
    local bin; bin="$(claude_bin "$CLAUDE_USER")"
    [[ -x "$bin" ]] || fail "Claude Code not found at $bin."
    info "Updating Claude Code..."
    as_user "$CLAUDE_USER" "$bin" update || warn "Update command reported an error."
    if [[ -f "$SERVICE_FILE" && -n "${CLAUDE_WORKDIR:-}" && -n "${CLAUDE_RC_NAME:-}" ]]; then
        ( write_service ) || warn "Remote Control quits at start. Choose Logs to see why."
    else
        systemctl restart "$SERVICE_NAME"
    fi
    ok "Updated to $(as_user "$CLAUDE_USER" "$bin" --version 2>/dev/null | head -1). Service restarted."
    if [[ -n "$(pkg_ver claude-desktop)" ]]; then
        info "Updating Claude Desktop..."
        apt-get update -qq
        DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --only-upgrade claude-desktop >/dev/null \
            || warn "Claude Desktop update failed."
        ok "Claude Desktop $(pkg_ver claude-desktop). Restart the app (or reboot) to use it."
        if [[ -n "$(pkg_ver firefox)" && ! -e /snap/bin/firefox ]]; then
            DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --only-upgrade firefox >/dev/null \
                || warn "Firefox update failed."
        else
            install_browser
        fi
    fi
}

# --- Static IP ---------------------------------------------------------------
# Pins the VM's LAN address so tunnel routes survive reboots. Uses 'netplan try',
# which reverts automatically if you do not confirm within 120 seconds.
do_static_ip() {
    command -v netplan >/dev/null || fail "netplan not found (not Ubuntu?)."
    local iface cur_cidr cur_ip prefix gw mac new_ip dns
    iface="$(ip route show default | awk '{print $5; exit}')"
    [[ -n "$iface" ]] || fail "No default route found."
    cur_cidr="$(ip -4 -o addr show dev "$iface" | awk '{print $4; exit}')"
    cur_ip="${cur_cidr%/*}"; prefix="${cur_cidr#*/}"
    gw="$(ip route show default | awk '{print $3; exit}')"
    mac="$(cat "/sys/class/net/${iface}/address")"

    banner "Static IP"
    warn "Run this from the Proxmox console, not SSH/Webmin: the connection drops when the IP changes."
    echo "  Interface  ${iface}"
    echo "  Current    ${cur_cidr}  (gateway ${gw})"
    echo ""
    info "Pick a high address (e.g. .200-.250) the router is unlikely to hand out."
    new_ip="$(ask "Static IP" "$cur_ip")"
    [[ "$new_ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || fail "Invalid IP address."
    prefix="$(ask "Prefix length" "$prefix")"
    gw="$(ask "Gateway" "$gw")"
    dns="$(ask "DNS servers (comma separated)" "${gw}, 1.1.1.1")"

    if [[ "$new_ip" != "$cur_ip" ]] && ping -c 2 -W 1 "$new_ip" >/dev/null 2>&1; then
        fail "${new_ip} already answers ping. Another device is using it; pick another."
    fi

    confirm "Apply ${new_ip}/${prefix} via ${gw} on ${iface}?" "N" || { info "Cancelled."; return 0; }

    local bak
    bak="/root/netplan-backup-$(date +%F-%H%M%S)"
    mkdir -p "$bak"
    cp -a /etc/netplan/. "$bak/"
    ok "Backed up /etc/netplan to ${bak}."

    # Stop cloud-init from regenerating network config on boot.
    if [[ -d /etc/cloud/cloud.cfg.d ]]; then
        echo "network: {config: disabled}" > /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
    fi

    find /etc/netplan -maxdepth 1 -name '*.yaml' -delete
    cat > /etc/netplan/01-static.yaml <<EOF
network:
  version: 2
  ethernets:
    ${iface}:
      match:
        macaddress: ${mac}
      set-name: ${iface}
      dhcp4: false
      dhcp6: true
      addresses: [${new_ip}/${prefix}]
      routes:
        - to: default
          via: ${gw}
      nameservers:
        addresses: [${dns}]
EOF
    chmod 600 /etc/netplan/01-static.yaml

    echo ""
    info "From another device run:  ping ${new_ip}"
    info "If it replies, press ENTER below to keep it. Otherwise wait and it reverts."
    echo ""
    netplan try --timeout 120 </dev/tty || true

    if ip -4 -o addr show dev "$iface" | grep -q " ${new_ip}/"; then
        ok "Static IP ${new_ip} active and saved."
        info "Update any Cloudflare tunnel routes that used the old IP (refresh the page between edits)."
    else
        warn "New IP not active; restoring previous netplan files."
        find /etc/netplan -maxdepth 1 -name '*.yaml' -delete
        cp -a "$bak/." /etc/netplan/
        netplan apply || true
        fail "Reverted. Nothing changed."
    fi
}

# --- Desktop (Claude Desktop in the browser) ---------------------------------
# Claude Desktop is a GUI app. KasmVNC runs a lean XFCE desktop as a boot
# service and streams it to any browser (same tech as the kasmweb/brave
# container), so the app's Chat, with folders on this VM, is reachable remotely.
pkg_ver()        { dpkg-query -W -f='${Version}' "$1" 2>/dev/null || true; }
autostart_file() { echo "$(user_home "$1")/.config/autostart/claude-desktop.desktop"; }
noblank_file()   { echo "$(user_home "$1")/.config/autostart/no-blank.desktop"; }

# One-line summary for Status.
desktop_state() {
    local u="$1" ver svc masked=0 t
    ver="$(pkg_ver claude-desktop)"
    [[ -n "$ver" ]] || { echo "not installed"; return; }
    svc="$(systemctl is-active "$DESKTOP_SERVICE" 2>/dev/null || true)"
    for t in $SLEEP_TARGETS; do
        [[ "$(systemctl is-enabled "$t" 2>/dev/null || true)" == "masked" ]] && masked=$((masked + 1))
    done
    echo "app ${ver}, ${DESKTOP_SERVICE} ${svc:-inactive}, https://$(hostname -I 2>/dev/null | awk '{print $1}'):${DESKTOP_PORT}, sleep ${masked}/4 masked"
}

# Earlier versions used LightDM auto-login on the console. KasmVNC replaces it;
# two sessions would start two copies of the app.
remove_autologin() {
    [[ -f "$AUTOLOGIN_FILE" ]] || systemctl is-enabled --quiet lightdm 2>/dev/null || return 0
    info "Switching off the console auto-login (KasmVNC replaces it)..."
    rm -f "$AUTOLOGIN_FILE"
    systemctl disable --now lightdm >/dev/null 2>&1 || true
    systemctl set-default multi-user.target >/dev/null
    ok "Console auto-login removed."
}

install_kasmvnc() {
    if [[ -n "$(pkg_ver kasmvncserver)" ]]; then
        ok "KasmVNC already installed ($(pkg_ver kasmvncserver))."
        return 0
    fi
    local codename arch url tmp
    codename="$(. /etc/os-release && echo "${VERSION_CODENAME:-}")"
    arch="$(dpkg --print-architecture)"
    info "Finding the KasmVNC package for ${codename} (${arch})..."
    local assets
    assets="$(curl -fsSL https://api.github.com/repos/kasmtech/KasmVNC/releases/latest \
        | grep -o '"browser_download_url": *"[^"]*\.deb"' | cut -d'"' -f4)" \
        || fail "Cannot reach GitHub to find KasmVNC."
    url="$(grep "/kasmvncserver_[a-z]*_${codename}_[^/]*_${arch}\.deb$" <<<"$assets" | head -1 || true)"
    if [[ -z "$url" ]]; then
        url="$(grep "/kasmvncserver_ubuntu_noble_[^/]*_${arch}\.deb$" <<<"$assets" | head -1 || true)"
        [[ -n "$url" ]] || fail "No KasmVNC package for ${codename}/${arch}."
        warn "No KasmVNC build for ${codename}; using the Ubuntu 24.04 (noble) one."
    fi
    tmp="$(mktemp -d)"
    curl -fsSLo "${tmp}/${url##*/}" "$url" || fail "KasmVNC download failed."
    apt-get install -y -qq "${tmp}/${url##*/}" >/dev/null || fail "KasmVNC install failed."
    rm -rf "$tmp"
    ok "KasmVNC $(pkg_ver kasmvncserver) installed."
}

# Browser login for KasmVNC: username = the Linux user, password asked here.
set_kasm_password() {
    local home pw pw2; home="$(user_home "$CLAUDE_USER")"
    if [[ -f "${home}/.kasmpasswd" ]] && ! confirm "Browser login already set. Change the password?" "N"; then
        return 0
    fi
    while true; do
        read -rsp "  Browser login password for '${CLAUDE_USER}' (min 6 chars): " pw </dev/tty; echo ""
        read -rsp "  Repeat: " pw2 </dev/tty; echo ""
        [[ "$pw" == "$pw2" && ${#pw} -ge 6 ]] && break
        warn "Passwords differ or are too short. Try again."
    done
    printf '%s\n%s\n' "$pw" "$pw" | as_user "$CLAUDE_USER" kasmvncpasswd -u "$CLAUDE_USER" -wo "${home}/.kasmpasswd" >/dev/null \
        || fail "Could not set the browser login."
    chmod 600 "${home}/.kasmpasswd"
    ok "Browser login set (user '${CLAUDE_USER}')."
}

write_kasm_config() {
    local home preset fps qmin qmax override scroll=true
    home="$(user_home "$CLAUDE_USER")"
    preset="${CLAUDE_STREAM:-$STREAM_DEFAULT}"
    case "$preset" in
        quality)  fps=60; qmin=5; qmax=6; override=true ;;
        balanced) fps=30; qmin=5; qmax=7; override=false; scroll=false ;;
        *)        fps=30; qmin=3; qmax=6; override=false; preset="performance" ;;
    esac
    mkdir -p "${home}/.vnc"
    cat > "${home}/.vnc/kasmvnc.yaml" <<EOF
# Written by setup-claudeubuntu.sh (streaming mode: ${preset}).
# Change it from the installer menu, not here: Install rewrites this file.
network:
  protocol: http
  interface: 0.0.0.0
  websocket_port: ${DESKTOP_PORT}
  ssl:
    require_ssl: true
desktop:
  resolution:
    width: 1920
    height: 1080
  allow_resize: true
runtime_configuration:
  allow_client_to_override_kasm_server_settings: ${override}
encoding:
  max_frame_rate: ${fps}
  rect_encoding_mode:
    min_quality: ${qmin}
    max_quality: ${qmax}
  video_encoding_mode:
    enter_video_encoding_mode:
      area_threshold: 100%
  scrolling:
    detect_vertical_scrolling: ${scroll}
EOF
    cat > "${home}/.vnc/xstartup" <<'EOF'
#!/bin/sh
unset SESSION_MANAGER DBUS_SESSION_BUS_ADDRESS
exec dbus-launch --exit-with-session startxfce4
EOF
    chmod 755 "${home}/.vnc/xstartup"
    touch "${home}/.vnc/.de-was-selected"
    chown -R "$CLAUDE_USER:" "${home}/.vnc"

    local mount_dep="" mnt
    mnt="$(findmnt -n -o TARGET --target "$CLAUDE_WORKDIR" 2>/dev/null || true)"
    [[ -n "$mnt" && "$mnt" != "/" ]] && mount_dep="RequiresMountsFor=${mnt}"

    cat > "$DESKTOP_SERVICE_FILE" <<EOF
[Unit]
Description=Claude Desktop in the browser (KasmVNC)
After=network-online.target
Wants=network-online.target
${mount_dep}

[Service]
Type=forking
User=${CLAUDE_USER}
SupplementaryGroups=ssl-cert
Environment=HOME=${home}
WorkingDirectory=${home}
ExecStartPre=-/usr/bin/vncserver -kill ${DESKTOP_DISPLAY}
ExecStart=/usr/bin/vncserver ${DESKTOP_DISPLAY}
ExecStop=/usr/bin/vncserver -kill ${DESKTOP_DISPLAY}
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable "$DESKTOP_SERVICE" >/dev/null 2>&1
    systemctl restart "$DESKTOP_SERVICE"
    sleep 5
    systemctl is-active --quiet "$DESKTOP_SERVICE" \
        || fail "KasmVNC failed to start. Run this again and choose Logs to see why."
    ok "Boot service '${DESKTOP_SERVICE}' enabled and running."
}

# Packages and files for the browser desktop. Idempotent; the browser password
# and the KasmVNC config are done afterwards by do_install.
install_desktop() {
    local home; home="$(user_home "$CLAUDE_USER")"
    info "XFCE + Claude Desktop will run as '${CLAUDE_USER}', streamed by KasmVNC on port ${DESKTOP_PORT}."

    export DEBIAN_FRONTEND=noninteractive
    info "Installing a minimal XFCE desktop (several minutes)..."
    apt-get update -qq
    # shellcheck disable=SC2086
    apt-get install -y -qq --no-install-recommends $DESKTOP_PKGS >/dev/null \
        || fail "Desktop package install failed."
    ok "Desktop installed."

    remove_autologin

    # shellcheck disable=SC2086
    systemctl mask $SLEEP_TARGETS >/dev/null 2>&1
    mkdir -p "${home}/.config/autostart"
    cat > "$(noblank_file "$CLAUDE_USER")" <<'EOF'
[Desktop Entry]
Type=Application
Name=Disable screen blanking and compositing
Exec=sh -c "xset s off -dpms s noblank; xfconf-query -c xfce4-power-manager -p /xfce4-power-manager/dpms-enabled -n -t bool -s false; xfconf-query -c xfce4-screensaver -p /saver/enabled -n -t bool -s false; xfconf-query -c xfwm4 -p /general/use_compositing -n -t bool -s false"
EOF
    ok "Sleep/suspend masked, screen blanking off."

    if [[ -z "$(pkg_ver claude-desktop)" ]]; then
        info "Adding Anthropic's apt repository..."
        curl -fsSLo "$DESKTOP_KEY_FILE" "$DESKTOP_KEY_URL" || fail "Key download failed. Check access to downloads.claude.ai."
        gpg --show-keys --with-colons "$DESKTOP_KEY_FILE" 2>/dev/null | grep -q "^fpr:::::::::${DESKTOP_KEY_FPR}:" \
            || { rm -f "$DESKTOP_KEY_FILE"; fail "Signing key fingerprint mismatch. Not installing."; }
        echo "$DESKTOP_REPO_LINE" > "$DESKTOP_REPO_FILE"
        apt-get update -qq
        info "Installing claude-desktop..."
        apt-get install -y -qq claude-desktop >/dev/null || fail "claude-desktop install failed."
    fi
    ok "Claude Desktop $(pkg_ver claude-desktop) installed."

    cat > "$(autostart_file "$CLAUDE_USER")" <<'EOF'
[Desktop Entry]
Type=Application
Name=Claude
Exec=claude-desktop
EOF
    chown -R "$CLAUDE_USER:" "${home}/.config"
    ok "Claude Desktop starts with the desktop."

    install_browser
    install_kasmvnc
    usermod -aG ssl-cert "$CLAUDE_USER"
}

# Firefox for links the app opens (Update available, sign-in pages). Ubuntu's
# snap build refuses to start inside the desktop service, so use Mozilla's .deb.
install_browser() {
    local home; home="$(user_home "$CLAUDE_USER")"
    export DEBIAN_FRONTEND=noninteractive
    if command -v snap >/dev/null && snap list firefox >/dev/null 2>&1; then
        info "Replacing the snap Firefox (it cannot start in this desktop)..."
        snap remove firefox >/dev/null 2>&1 || warn "Could not remove the snap Firefox."
    fi
    # Newer Firefox packages may ship their own mozilla.sources; a second entry breaks apt.
    if [[ ! -f "$BROWSER_REPO_FILE" && ! -f /etc/apt/sources.list.d/mozilla.sources ]]; then
        info "Adding Mozilla's apt repository..."
        install -d -m 0755 /etc/apt/keyrings
        curl -fsSLo "$BROWSER_KEY_FILE" "$BROWSER_KEY_URL" || fail "Key download failed. Check access to packages.mozilla.org."
        gpg --show-keys --with-colons "$BROWSER_KEY_FILE" 2>/dev/null | grep -q "^fpr:::::::::${BROWSER_KEY_FPR}:" \
            || { rm -f "$BROWSER_KEY_FILE"; fail "Mozilla key fingerprint mismatch. Not installing."; }
        echo "$BROWSER_REPO_LINE" > "$BROWSER_REPO_FILE"
        printf 'Package: *\nPin: origin packages.mozilla.org\nPin-Priority: 1000\n' > "$BROWSER_PIN_FILE"
    fi
    apt-get update -qq
    apt-get install -y -qq --allow-downgrades firefox xdg-utils >/dev/null || fail "Firefox install failed."
    [[ -x /usr/bin/firefox ]] || fail "Firefox installed but /usr/bin/firefox is missing."

    # Links reach the browser through www-browser, xdg-open and Xfce's helper.
    [[ -L /usr/local/bin/www-browser ]] && rm -f /usr/local/bin/www-browser
    local alt
    for alt in www-browser x-www-browser; do
        update-alternatives --install "/usr/bin/${alt}" "$alt" /usr/bin/firefox 200 >/dev/null
        update-alternatives --set "$alt" /usr/bin/firefox >/dev/null
    done
    as_user "$CLAUDE_USER" xdg-mime default firefox.desktop text/html x-scheme-handler/http x-scheme-handler/https 2>/dev/null || true
    mkdir -p "${home}/.config/xfce4"
    touch "${home}/.config/xfce4/helpers.rc"
    sed -i '/^WebBrowser=/d' "${home}/.config/xfce4/helpers.rc"
    echo "WebBrowser=firefox" >> "${home}/.config/xfce4/helpers.rc"
    rm -f "${home}/.local/share/xfce4/helpers/firefox-snap.desktop"
    chown -R "$CLAUDE_USER:" "${home}/.config"
    ok "Firefox $(pkg_ver firefox) is the default browser."
}

# --- Settings ----------------------------------------------------------------
set_streaming() { # set_streaming performance|balanced|quality
    load_conf
    [[ -n "${CLAUDE_USER:-}" && -f "$DESKTOP_SERVICE_FILE" ]] || fail "Desktop not installed. Run Install first."
    CLAUDE_STREAM="$1"
    save_conf
    write_kasm_config
    ok "Streaming set to $(stream_label "$1"). Reload the desktop page in the browser."
}

# do_settings [performance|balanced|quality|ip]; no argument shows the menu.
do_settings() {
    local pick="${1:-}"
    if [[ -z "$pick" ]]; then
        load_conf
        banner "Settings"
        info "Streaming: $( [[ -f "$DESKTOP_SERVICE_FILE" ]] && stream_label "${CLAUDE_STREAM:-$STREAM_DEFAULT}" || echo 'desktop not installed' )"
        menu "Improve stream performance" "Improve stream quality" \
             "Balance stream|work networks: sharper scrolling" "Fix VM IP" "Back"
        case "$CHOICE" in
            "Improve stream performance") pick=performance ;;
            "Improve stream quality")     pick=quality ;;
            "Balance stream")             pick=balanced ;;
            "Fix VM IP")                  pick=ip ;;
            Back)                         return 0 ;;
        esac
    fi
    case "$pick" in
        performance|balanced|quality) set_streaming "$pick" ;;
        ip)                           do_static_ip ;;
        *) fail "Unknown setting '${pick}'. Use: performance | balanced | quality | ip" ;;
    esac
}

# --- Connectors --------------------------------------------------------------
# External accounts Claude Code on this VM can use. The claude.ai connectors do
# not reach a session that runs here, so each one is logged in on the VM itself.

# The user Claude runs as (saved settings, else the sudo caller, else uid 1000).
claude_user() {
    load_conf
    local u="${CLAUDE_USER:-}"
    if [[ -z "$u" ]]; then
        u="${SUDO_USER:-}"
        [[ -z "$u" || "$u" == "root" ]] && u="$(getent passwd 1000 | cut -d: -f1)"
    fi
    echo "$u"
}

# "logged in as <account>" | "not connected" | "gh not installed"
gh_state() {
    local u="$1" acct
    command -v gh >/dev/null || { echo "not connected (gh not installed)"; return; }
    acct="$(as_user "$u" gh api user --jq .login 2>/dev/null || true)"
    [[ -n "$acct" ]] && echo "logged in as ${acct}" || echo "not connected"
}

connect_github() {
    local u; u="$(claude_user)"
    [[ -n "$u" ]] || fail "Could not work out which user Claude runs as. Run Install first."
    if ! command -v gh >/dev/null; then
        info "Installing the GitHub command-line tool (gh)..."
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq
        apt-get install -y -qq gh >/dev/null 2>&1 || fail "Could not install gh."
    fi
    echo ""
    info "Logging '${u}' in to GitHub. A one-time code appears below; open the link"
    info "shown on any device, sign in to GitHub, enter the code, then come back here."
    echo ""
    as_user "$u" gh auth login --hostname github.com --git-protocol https --web </dev/tty         || fail "GitHub login did not complete. Run Connectors again to retry."
    as_user "$u" gh auth setup-git >/dev/null 2>&1 || warn "Could not wire git to gh; 'git push' may still ask for a password."
    ok "GitHub: $(gh_state "$u"). Claude Code on this VM can now read and push your repos."
}

disconnect_github() {
    local u; u="$(claude_user)"
    command -v gh >/dev/null || { info "GitHub is not connected."; return 0; }
    confirm "Log '${u}' out of GitHub on this VM?" "N" || { info "Cancelled."; return 0; }
    as_user "$u" gh auth logout --hostname github.com >/dev/null 2>&1 || true
    ok "GitHub disconnected. (The gh tool stays installed; reconnect any time.)"
}

do_connectors() {
    local pick="${1:-}"
    if [[ -z "$pick" ]]; then
        local u; u="$(claude_user)"
        banner "Connectors"
        info "GitHub: $(gh_state "$u")"
        menu "Connect GitHub" "Disconnect GitHub" "Back"
        case "$CHOICE" in
            "Connect GitHub")    pick=github ;;
            "Disconnect GitHub") pick=github-off ;;
            Back)                return 0 ;;
        esac
    fi
    case "$pick" in
        github)     connect_github ;;
        github-off) disconnect_github ;;
        *) fail "Unknown connector '${pick}'. Use: github | github-off" ;;
    esac
}

desktop_remove() {
    systemctl disable --now "$DESKTOP_SERVICE" >/dev/null 2>&1 || true
    rm -f "$DESKTOP_SERVICE_FILE"
    systemctl daemon-reload
    apt-get remove -y -qq claude-desktop >/dev/null 2>&1 || true
    rm -f "$DESKTOP_REPO_FILE"
    [[ -n "${CLAUDE_USER:-}" ]] && rm -f "$(autostart_file "$CLAUDE_USER")"
    ok "Claude Desktop and its service removed."

    if confirm "Also remove KasmVNC, the sleep mask and the XFCE desktop?" "N"; then
        remove_autologin
        if [[ -n "${CLAUDE_USER:-}" ]]; then
            local home; home="$(user_home "$CLAUDE_USER")"
            rm -rf "$(noblank_file "$CLAUDE_USER")" "${home}/.vnc" "${home}/.kasmpasswd"
        fi
        # shellcheck disable=SC2086
        systemctl unmask $SLEEP_TARGETS >/dev/null 2>&1 || true
        # shellcheck disable=SC2086
        apt-get remove -y -qq kasmvncserver $DESKTOP_PKGS lightdm lightdm-gtk-greeter firefox >/dev/null 2>&1 || true
        rm -f "$BROWSER_REPO_FILE" "$BROWSER_PIN_FILE" "$BROWSER_KEY_FILE"
        apt-get autoremove -y -qq >/dev/null 2>&1 || true
        ok "KasmVNC and the desktop removed."
    fi
}

# --- Uninstall ---------------------------------------------------------------
do_uninstall() {
    load_conf
    if [[ -n "$(pkg_ver claude-desktop)" ]] && confirm "Remove Claude Desktop and its browser desktop?" "Y"; then
        desktop_remove
    fi
    confirm "Remove the '${SERVICE_NAME}' boot service?" "N" || { info "Cancelled."; return 0; }
    systemctl disable --now "$SERVICE_NAME" 2>/dev/null || true
    rm -f "$SERVICE_FILE"
    systemctl daemon-reload
    [[ -n "${CLAUDE_USER:-}" ]] && as_user "$CLAUDE_USER" tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true
    ok "Service removed."

    if [[ -n "${CLAUDE_USER:-}" ]] && confirm "Also remove Claude Code and its login for '${CLAUDE_USER}'?" "N"; then
        local home; home="$(user_home "$CLAUDE_USER")"
        rm -rf "${home}/.local/bin/claude" "${home}/.local/share/claude" "${home}/.claude" "${home}/.claude.json"
        ok "Claude Code removed. Your files in ${CLAUDE_WORKDIR:-the working folder} are untouched."
    fi
    rm -f "$CONF_FILE"
}

# --- Logs --------------------------------------------------------------------
# Last lines of both services, so nobody has to remember journalctl.
do_logs() {
    banner "Logs"
    local svc
    for svc in "$SERVICE_NAME" "$DESKTOP_SERVICE"; do
        echo ""
        info "${svc} (latest last)"
        journalctl -u "$svc" -n 25 --no-pager -o short 2>/dev/null | sed 's/^/       /' || true
    done
    echo ""
    info "Remote Control lines tagged '${SERVICE_NAME}:' show its last screen before it stopped."
    info "Usual fix: choose Install, keep the defaults, answer y to 'Log in again?'."
}

# Main menu status line: is Remote Control connected?
rc_summary() {
    local u; u="$(claude_user)"
    if [[ -n "$u" ]] && command -v tmux >/dev/null && [[ "$(rc_state "$u")" == connected ]]; then
        ok "Remote Control connected."
    elif [[ -f "$SERVICE_FILE" ]]; then
        info "Remote Control not connected. Choose Status, then Logs."
    else
        info "Not installed yet. Choose Install."
    fi
}

# --- Dispatch ----------------------------------------------------------------
case "${1:-}" in
    install)   do_install;    exit 0 ;;
    status)    do_status;     exit 0 ;;
    update)    do_update;     exit 0 ;;
    settings)  do_settings "${2:-}"; exit 0 ;;
    connectors) do_connectors "${2:-}"; exit 0 ;;
    logs)      do_logs;       exit 0 ;;
    uninstall) do_uninstall;  exit 0 ;;
    "")        ;;
    *)         fail "Unknown option '$1'. Use: install | status | update | settings [performance|balanced|quality|ip] | connectors [github|github-off] | logs | uninstall" ;;
esac

while true; do
    banner "Claude Code + Claude Desktop on Ubuntu VM"
    rc_summary
    menu "Install|Claude Code (Remote Control) + Claude Desktop" "Status" "Update" "Settings" \
         "Connectors|GitHub login for Claude Code on this VM" "Logs|why Remote Control or the desktop stopped" "Uninstall"
    case "$CHOICE" in
        Install)    do_install ;;
        Status)     do_status ;;
        Update)     do_update ;;
        Settings)   do_settings ;;
        Connectors) do_connectors ;;
        Logs)       do_logs ;;
        Uninstall)  do_uninstall ;;
    esac
done
