#!/bin/sh
# uremot installer, served at https://get.uremot.com (the Cloudflare rewrite
# maps / to /install.sh on the releases bucket):
#
#   curl -fsSL https://get.uremot.com | sh
#   curl -fsSL https://get.uremot.com | sh -s -- --daemon   # + systemd unit (root, Linux)
#
# A new --daemon install stops, having changed nothing, when this system
# doesn't run systemd or no container engine answers; --no-containers waives
# the engine, for a Compute prepared before it or kept for the network alone.
#
# It installs the `uremot` binary: one executable whose role is `compute`
# (this machine hosts Instances, a daemon); `update` and `uninstall` are
# binary-wide. An AI harness installs nothing: it adds the hosted MCP door by
# URL (ADR-0016). Machines with a desktop to share belong on the desktop app
# instead: https://console.uremot.com/download. Design record: ADR-0012 and
# deploy/client-release/ARCHITECTURE.md, "The CLI embodiment".
set -eu

# UREMOT_LATEST_BASE_URL exists so the install flow can be tested end to end
# against a locally served alias tree; production use never sets it.
LATEST_BASE_URL="${UREMOT_LATEST_BASE_URL:-https://releases.uremot.com/client/releases/latest}"
# UREMOT_INSTALL_ROOT exists so the preflight can be tested against a test
# root, the way UREMOT_LATEST_BASE_URL tests the download; production use
# never sets it.
ROOT="${UREMOT_INSTALL_ROOT:-}"
BINARY_NAME="uremot"
INSTALL_DIR_ROOT="${ROOT}/usr/local/bin"
INSTALL_DIR_USER="${HOME:-/root}/.uremot/bin"
UNIT_FILE="${ROOT}/etc/systemd/system/uremot-compute.service"
# The directory systemd creates at boot: where it doesn't exist (OpenRC,
# runit, a container), systemctl fails partway through a unit install.
SYSTEMD_RUN_DIR="${ROOT}/run/systemd/system"

DAEMON=0
NO_CONTAINERS=0
for arg in "$@"; do
    case "$arg" in
        --daemon) DAEMON=1 ;;
        --no-containers) NO_CONTAINERS=1 ;;
        *) echo "Unknown argument: $arg" >&2; exit 1 ;;
    esac
done

err() { echo "error: $1" >&2; exit 1; }
info() { echo "--> $1"; }

# ---------------------------------------------------------------------------
# Platform: Linux x86_64 and aarch64, macOS as one universal binary, Windows
# x86_64 from Git Bash (MSYS) — the shell a Windows developer running
# `uremot publish` already has. The binary there is `uremot.exe`: on Windows
# the suffix is what makes a file a program, so it is part of the published
# name and of the installed one.
# ---------------------------------------------------------------------------
OS="$(uname -s)"
ARCH="$(uname -m)"
BIN_EXT=""
case "$OS" in
    Linux)
        case "$ARCH" in
            x86_64)          TARGET="linux-x86_64" ;;
            aarch64 | arm64) TARGET="linux-aarch64" ;;
            *)               err "Unsupported architecture: $ARCH" ;;
        esac
        ;;
    Darwin)
        TARGET="darwin-universal"
        [ "$DAEMON" -eq 0 ] || err "--daemon writes a systemd unit and is Linux only"
        ;;
    MINGW* | MSYS* | CYGWIN*)
        case "$ARCH" in
            x86_64) TARGET="windows-x86_64" BIN_EXT=".exe" ;;
            *)      err "Unsupported architecture: $ARCH" ;;
        esac
        [ "$DAEMON" -eq 0 ] || err "--daemon writes a systemd unit and is Linux only"
        ;;
    *) err "Unsupported operating system: $OS" ;;
esac
BINARY_FILE="${BINARY_NAME}${BIN_EXT}"
info "Detected platform: ${TARGET}"
info "By installing you agree to the Software License Agreement: https://uremot.com/legal/software-license"

# ---------------------------------------------------------------------------
# Dependencies
# ---------------------------------------------------------------------------
command -v curl >/dev/null 2>&1 || err "'curl' is required but not found in PATH"

# ---------------------------------------------------------------------------
# The stable URL for the current build
# ---------------------------------------------------------------------------
# Every release publishes every artifact or none of them, so releases/latest/
# always carries a complete, mutually consistent set and one fixed URL per
# platform is the whole lookup. Integrity is the TLS fetch plus running the
# binary before installing it; a checksum served from the same bucket the
# binary came from would prove nothing more.
BINARY_URL="${LATEST_BASE_URL}/uremot-${TARGET}${BIN_EXT}"

info "Binary URL: ${BINARY_URL}"

# ---------------------------------------------------------------------------
# Install location
# ---------------------------------------------------------------------------
IS_ROOT=0
if [ "$(id -u)" -eq 0 ]; then
    IS_ROOT=1
    INSTALL_DIR="$INSTALL_DIR_ROOT"
else
    INSTALL_DIR="$INSTALL_DIR_USER"
fi

if [ "$DAEMON" -eq 1 ] && [ "$IS_ROOT" -eq 0 ]; then
    err "--daemon requires root (run with sudo); it writes a systemd unit"
fi

# ---------------------------------------------------------------------------
# Download and verify
# ---------------------------------------------------------------------------
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

TMP_BIN="${TMP_DIR}/${BINARY_FILE}"
info "Downloading binary..."
curl -fsSL -o "$TMP_BIN" "$BINARY_URL" || err "Failed to download binary from $BINARY_URL"

chmod +x "$TMP_BIN"
# Running the binary is the integrity check: it proves the download is
# complete and executable on this machine before any existing install is
# replaced.
VERSION_LINE="$("$TMP_BIN" --version 2>&1)" || err "downloaded binary failed to run: ${VERSION_LINE}"
info "Downloaded ${VERSION_LINE}"

# ---------------------------------------------------------------------------
# Preflight, before anything moves
# ---------------------------------------------------------------------------
# A unit that already exists is a daemon install being upgraded (see the unit
# section). Only a new service install can stop: an upgrade warns and goes on,
# so a network-only Compute, or one whose engine is briefly down, upgrades as
# it always did.
UNIT_EXISTED=0
if [ "$IS_ROOT" -eq 1 ] && [ -f "$UNIT_FILE" ]; then
    DAEMON=1
    UNIT_EXISTED=1
fi
if [ "$DAEMON" -eq 1 ] && { ! command -v systemctl >/dev/null 2>&1 || [ ! -d "$SYSTEMD_RUN_DIR" ]; }; then
    echo "This system doesn't run systemd. Install without --daemon, then keep \`uremot compute run\` running under" >&2
    echo "your init system (OpenRC, runit, s6) or a supervisor: https://uremot.com/docs/add-a-linux-server#without-systemd" >&2
    exit 1
fi

# The staged binary's own probe, the one its daemon runs, so the installer and
# the Compute can't disagree. A state file of its own keeps any identity out
# of it: only `containers` is read.
case "$OS" in
    Linux)  ENGINE_INSTALL="Install Docker Engine: https://docs.docker.com/engine/install/" ;;
    Darwin) ENGINE_INSTALL="Install Docker Desktop (or another engine that serves the Docker socket): https://docs.docker.com/desktop/setup/install/mac-install/" ;;
    *)      ENGINE_INSTALL="Install Docker Desktop (or another engine that serves the Docker socket): https://docs.docker.com/desktop/setup/install/windows-install/" ;;
esac
ENGINE_WARN=0
MACHINE="$("$TMP_BIN" compute --state-file "${TMP_DIR}/probe.json" status --json 2>/dev/null)" || MACHINE=""
# Only the probe's own "no engine" stops: an answer that can't be read (a
# failed status, a staged binary without the field) is said, never a stop.
case "$MACHINE" in
    *'"containers":"available"'* | *'"containers":"blocked"'*) ;;
    # the engine is there and refuses this user: join its group, never reinstall
    # it (root, and so a --daemon install, is never refused)
    *'"containers_reason":"no permission"'*) ENGINE_WARN=3 ;;
    *'"containers":"unsupported"'*)
        if [ "$DAEMON" -eq 1 ] && [ "$UNIT_EXISTED" -eq 0 ] && [ "$NO_CONTAINERS" -eq 0 ]; then
            echo "No container engine answers here. ${ENGINE_INSTALL}" >&2
            echo "Then run this again, or add --no-containers to install without containers." >&2
            exit 1
        fi
        ENGINE_WARN=1
        ;;
    *) ENGINE_WARN=2 ;;
esac

# ---------------------------------------------------------------------------
# Install
# ---------------------------------------------------------------------------
mkdir -p "$INSTALL_DIR"
mv "$TMP_BIN" "${INSTALL_DIR}/${BINARY_FILE}"
info "Installed ${BINARY_NAME} to ${INSTALL_DIR}/${BINARY_FILE}"

# A pre-merge install is not carried over (ADR-0012, "Compatibility: none"):
# its daemon exits on the renamed API and its unit keeps restarting it, so say
# where it is rather than retiring it, which is a decision for its owner.
for OLD_UNIT in /etc/systemd/system/uremot-agent.service; do
    if [ -f "$OLD_UNIT" ]; then
        echo ""
        echo "NOTE: a pre-merge uremot-agent service exists at ${OLD_UNIT}. It cannot"
        echo "      reach the platform any more; stop and disable it, then enroll this binary:"
        echo "        systemctl disable --now uremot-agent"
    fi
done
# Both install dirs, not just the root one: a user-mode install leaves its
# pre-merge pair in INSTALL_DIR_USER, where this notice used to miss them.
for OLD_BIN in \
    "$INSTALL_DIR_ROOT/uremot-agent" "$INSTALL_DIR_ROOT/uremot-mcp" \
    "$INSTALL_DIR_USER/uremot-agent" "$INSTALL_DIR_USER/uremot-mcp"; do
    if [ -x "$OLD_BIN" ]; then
        echo "NOTE: pre-merge binary ${OLD_BIN} is no longer used; remove it when convenient."
    fi
done

# ---------------------------------------------------------------------------
# Systemd unit (--daemon, root only)
# ---------------------------------------------------------------------------
# A unit that already exists is a daemon install being upgraded: the unit is
# rewritten, and a daemon that was running is restarted onto the new binary.
# One an operator stopped stays stopped.
UNIT_RUNNING=0
if [ "$UNIT_EXISTED" -eq 1 ] && systemctl is-active --quiet uremot-compute; then
    UNIT_RUNNING=1
fi
if [ "$DAEMON" -eq 1 ]; then
    info "Creating systemd unit at ${UNIT_FILE}..."

    # HOME=/root pins the state file the daemon reads to the same
    # ~/.local/share/uremot/compute-state.json that `sudo uremot compute enroll`
    # writes, so enrollment and the service cannot disagree about identity.
    cat > "$UNIT_FILE" <<'EOF'
[Unit]
Description=Uremot compute daemon
After=network-online.target docker.service
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/uremot compute run
Restart=always
RestartSec=5
Environment=HOME=/root

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable uremot-compute
    if [ "$UNIT_RUNNING" -eq 1 ]; then
        systemctl restart uremot-compute
        info "Service restarted on the new binary"
    elif [ "$UNIT_EXISTED" -eq 1 ]; then
        info "Service left stopped, as it was; start it with: systemctl start uremot-compute"
    else
        info "Service enabled (not started: enroll first, see below)"
    fi
fi

# ---------------------------------------------------------------------------
# Next steps
# ---------------------------------------------------------------------------
# Every command printed below, in full while the directory isn't on PATH: a
# fresh shell can't find a bare `uremot` yet (#3373; the installer QA run of
# 2026-11-13, I1).
UREMOT_CMD="${BINARY_NAME}"
if [ "$IS_ROOT" -eq 0 ]; then
    case ":${PATH}:" in
        *":${INSTALL_DIR}:"*) ;;
        # shellcheck disable=SC2088 # shown for the person to type
        *) UREMOT_CMD="~/.uremot/bin/${BINARY_NAME}" ;;
    esac
fi
echo ""
echo "${VERSION_LINE} installed."
echo ""
echo "To host Instances on this machine, enroll it into a workspace by signing"
echo "in, which records you as its owner (approve the code it prints in your"
echo "browser):"
echo ""
if [ "$DAEMON" -eq 1 ]; then
    # The unit reads root's state file, so enrollment must run as root too.
    # Under `curl | sudo sh` the next command is typed in the invoking user's
    # shell, where a bare `uremot compute enroll` writes that user's state file
    # and the service keeps restarting on "not enrolled".
    AS_ROOT=""
    [ -n "${SUDO_USER:-}" ] && AS_ROOT="sudo "
    ENROLL="${AS_ROOT}${UREMOT_CMD} compute enroll"
    echo "  ${ENROLL} --sign-in"
    echo ""
    echo "Enroll starts the service; it comes online within a few seconds."
else
    ENROLL="${UREMOT_CMD} compute enroll"
    echo "  ${ENROLL} --sign-in"
    echo "  ${UREMOT_CMD} compute run"
    echo ""
    echo "It's a Compute only while that runs, and nothing starts it again after a"
    echo "closed shell or a reboot: keep it running in tmux or under a supervisor."
fi
echo ""
echo "Or enroll with a one-time grant from the Console's Add a Compute page"
echo "(Headless Linux server, then Create enrollment grant), pasted when it asks:"
echo ""
echo "  ${ENROLL} --grant-stdin"
echo ""
echo "A grant alone enrolls a shared workspace machine: workspace members and"
echo "their agents can launch Instances and hire agents on it. Whoever operates"
echo "the machine can access its workloads and credentials. Use --sign-in for"
echo "a personal machine that only you and your agents may launch on."
echo ""
echo "A script can pipe the grant in, or set UREMOT_COMPUTE_GRANT. --grant=<token>"
echo "still works, but every process on this machine can read an argument, and"
echo "your shell history keeps it. If you use it, keep the '=': one token in thirty"
echo "starts with '-', which a separate argument would misparse as a flag."

# Near the end, so the step to take is never the line that scrolls away: a
# plain install, --no-containers and an upgrade go on without an engine.
if [ "${ENGINE_WARN:-0}" -eq 1 ]; then
    echo ""
    echo "No container engine answers here. ${ENGINE_INSTALL}"
    echo "This Compute finds it within a few seconds; no restart needed."
elif [ "${ENGINE_WARN:-0}" -eq 3 ]; then
    echo ""
    echo "Docker is installed, but this user can't reach it: \`sudo usermod -aG docker \$USER\`, then log out and in, and start \`${UREMOT_CMD} compute run\` again."
elif [ "${ENGINE_WARN:-0}" -eq 2 ]; then
    echo ""
    echo "Couldn't check for a container engine. \`${UREMOT_CMD} compute status\` says whether one answers."
fi

# Last of all: until the directory is on PATH, every command above is
# `uremot: command not found` (#3373, discovery §2 A).
if [ "$IS_ROOT" -eq 0 ]; then
    case ":${PATH}:" in
        *":${INSTALL_DIR}:"*) ;;
        *)
            echo ""
            echo "NOTE: ${INSTALL_DIR} is not in your PATH."
            echo "Add this to your shell profile (~/.bashrc, ~/.zshrc, ...):"
            echo ""
            echo "  export PATH=\"\$PATH:${INSTALL_DIR}\""
            echo ""
            echo "Then open a new shell, or run that line now."
            # Git Bash's PATH is its own; PowerShell and cmd read the Windows
            # user PATH, which this script does not edit.
            if [ -n "$BIN_EXT" ]; then
                echo ""
                # printf, not echo: dash's echo eats the backslashes.
                printf '%s\n' 'For PowerShell and cmd, add %USERPROFILE%\.uremot\bin to your user PATH'
                echo "(Settings > System > About > Advanced system settings > Environment Variables)."
            fi
            ;;
    esac
fi

# The one next command, as the very last line (#3373, S4), in full while the
# directory isn't on PATH: a fresh shell can't find a bare `uremot` yet.
# `uremot setup` doesn't run on Windows, where the desktop app is the path.
if [ -z "$BIN_EXT" ]; then
    echo ""
    echo "Next, sign in and connect your AI harnesses:"
    echo ""
    echo "  ${UREMOT_CMD} setup"
fi
