#!/usr/bin/env bash # DIY build machine, Linux (51.40-T21, T22): make this computer, or a virtual machine, a build machine for DIY's lanes. # # sudo ./setup-linux.sh install what DIY's builds and tests need, and the diy-worker user (safe to run again) # sudo ./setup-linux.sh --check say what is there and what is missing, with the step to fix each (changes nothing) # sudo ./setup-linux.sh --join [CODE] join this machine to your DIY: on your DIY's computer run `diy worker add ` first, # then type the code it shows here # sudo ./setup-linux.sh --remove undo what this script did (the user and its folder, the toolchains, the packages it installed) # # Options: --tailscale (also install Tailscale with its own installer from tailscale.com, not pinned, and sign in with your own # `tailscale up`; the script never holds a key), --ssh-port N # (sshd listens on N, for WSL, where Windows may hold 22), --keep-packages (with --remove: leave the system packages), --dry-run (print # what would run), --yes (no question before --remove), -h/--help. # # What it installs, and why (DIY's builds and tests, as on the laptop the lanes move from): # packages a C toolchain, clang and mold (the linker every lane uses), pkg-config, git, curl, openssh-server, and the Tauri libraries # (WebKitGTK 4.1, GTK 3, AppIndicator, librsvg, libxdo, libudev, OpenSSL): Ubuntu 22.04+, Debian 12+, Fedora 39+ # chrome Google Chrome (x86_64; Chromium on arm64) at /opt/google/chrome/chrome, where DIY's browser walks look (BENCH_CHROME): # Google's newest package over TLS, not pinned, and it adds Google's apt source (Debian, Ubuntu) for its own updates # diy-worker a user with no password and no sudo, signed in by key only (sshd drop-in), with lingering on so its lane has a # systemd user session; its work folder is ~diy-worker/work (one build folder per seat under it) # rust rustup for diy-worker, toolchain RUST_VERSION below, with clippy and rustfmt # node, pnpm Node NODE_VERSION (checked against the sha256 below) under /opt/diy-worker, pnpm PNPM_VERSION # zig Zig ZIG_VERSION (the same pin and hashes as DIY's scripts/setup-zig.sh) under /opt/diy-worker # lane ~diy-worker/.config/diy-worker/lane.env: the memory cap, the memory to wait for and the cargo jobs, from this machine's # memory and cores; ~diy-worker/.cargo/config.toml links with mold and builds incrementally # # Nothing personal and no secret is in this file or put on the machine by it: no name, no address, no key, no token. The one key that # lands here is the public key of your DIY, by --join, for diy-worker only, after you typed the code your DIY showed you. # # Exit: 0 done (or, with --check, everything is there); 1 something failed or is missing (the lines above say what); 2 a usage mistake; # 3 --join waited and nobody came (or the code typed here was not the one shown). set -euo pipefail # Everything runs from main, called on the last line: a download cut short is a syntax error and runs nothing (51.40 review 1, B1). # The last line passes --end-of-script after the arguments: a cut inside that line, even at `main` itself, runs nothing (review 2, N6). main() { if [ "$#" -eq 0 ] || [ "${!#}" != --end-of-script ]; then echo "setup-linux.sh: this copy is cut short (the download did not finish): nothing was done. Download it again." >&2 exit 1 fi set -- "${@:1:$#-1}" ARGS="$*" SETUP_VERSION=1 RUST_VERSION="1.97.1" NODE_VERSION="24.12.0" NODE_SHA256_X64="bdebee276e58d0ef5448f3d5ac12c67daa963dd5e0a9bb621a53d1cefbc852fd" NODE_SHA256_ARM64="a06d42807fb500f7459e5f3fa6cb431447352826ee6f07e14adfeec58a1b3210" PNPM_VERSION="10.28.1" ZIG_VERSION="0.17.0" ZIG_SHA256_X64="1cbe9df9f27e6b78d14ccbca43b6703a404ef79ef1c463de901d7f088d4e2026" ZIG_SHA256_ARM64="9e8d11661d4ae3bd57702a3832781e23ad151dde5798e16a5ccd503f65234ff8" WUSER="diy-worker" PAIR_PORT_DEFAULT=7491 # ---- test seam ----------------------------------------------------------------------------------------------------------- # DIY_WORKER_ROOT puts every file this script reads or writes under a folder (tools/worker/test runs it so, with stand-ins for the # system's commands on PATH). Only then may it run without root, and only then are the DIY_WORKER_TEST_* overrides read. ROOT="${DIY_WORKER_ROOT:-}" if [ -n "$ROOT" ]; then NODE_SHA256_X64="${DIY_WORKER_TEST_NODE_SHA256:-$NODE_SHA256_X64}"; NODE_SHA256_ARM64="${DIY_WORKER_TEST_NODE_SHA256:-$NODE_SHA256_ARM64}" ZIG_SHA256_X64="${DIY_WORKER_TEST_ZIG_SHA256:-$ZIG_SHA256_X64}"; ZIG_SHA256_ARM64="${DIY_WORKER_TEST_ZIG_SHA256:-$ZIG_SHA256_ARM64}" fi R() { printf '%s%s' "$ROOT" "$1"; } # ---- arguments ----------------------------------------------------------------------------------------------------------- MODE=install JOIN=0 JOIN_CODE="${DIY_WORKER_JOIN_CODE:-}" TAILSCALE=0 SSH_PORT="" PAIR_PORT="${DIY_WORKER_PAIR_PORT:-$PAIR_PORT_DEFAULT}" PAIR_WAIT="${DIY_WORKER_PAIR_WAIT:-600}" KEEP_PACKAGES=0 DRY=0 YES=0 usage() { # the header above, also when the script is piped (there is no file to read then) cat <<'USAGE' DIY build machine, Linux (51.40-T21, T22): make this computer, or a virtual machine, a build machine for DIY's lanes. sudo ./setup-linux.sh install what DIY's builds and tests need, and the diy-worker user (safe to run again) sudo ./setup-linux.sh --check say what is there and what is missing, with the step to fix each (changes nothing) sudo ./setup-linux.sh --join [CODE] join this machine to your DIY: on your DIY's computer run `diy worker add ` first, then type the code it shows here sudo ./setup-linux.sh --remove undo what this script did (the user and its folder, the toolchains, the packages it installed) Options: --tailscale (also install Tailscale with its own installer from tailscale.com, not pinned, and sign in with your own `tailscale up`; the script never holds a key), --ssh-port N (sshd listens on N, for WSL, where Windows may hold 22), --keep-packages (with --remove: leave the system packages), --dry-run (print what would run), --yes (no question before --remove), -h/--help. What it installs, and why (DIY's builds and tests, as on the laptop the lanes move from): packages a C toolchain, clang and mold (the linker every lane uses), pkg-config, git, curl, openssh-server, and the Tauri libraries (WebKitGTK 4.1, GTK 3, AppIndicator, librsvg, libxdo, libudev, OpenSSL): Ubuntu 22.04+, Debian 12+, Fedora 39+ chrome Google Chrome (x86_64; Chromium on arm64) at /opt/google/chrome/chrome, where DIY's browser walks look (BENCH_CHROME): Google's newest package over TLS, not pinned, and it adds Google's apt source (Debian, Ubuntu) for its own updates diy-worker a user with no password and no sudo, signed in by key only (sshd drop-in), with lingering on so its lane has a systemd user session; its work folder is ~diy-worker/work (one build folder per seat under it) rust rustup for diy-worker, toolchain RUST_VERSION below, with clippy and rustfmt node, pnpm Node NODE_VERSION (checked against the sha256 below) under /opt/diy-worker, pnpm PNPM_VERSION zig Zig ZIG_VERSION (the same pin and hashes as DIY's scripts/setup-zig.sh) under /opt/diy-worker lane ~diy-worker/.config/diy-worker/lane.env: the memory cap, the memory to wait for and the cargo jobs, from this machine's memory and cores; ~diy-worker/.cargo/config.toml links with mold and builds incrementally Nothing personal and no secret is in this file or put on the machine by it: no name, no address, no key, no token. The one key that lands here is the public key of your DIY, by --join, for diy-worker only, after you typed the code your DIY showed you. Exit: 0 done (or, with --check, everything is there); 1 something failed or is missing (the lines above say what); 2 a usage mistake; 3 --join waited and nobody came (or the code typed here was not the one shown). USAGE } while [ $# -gt 0 ]; do case "$1" in --check) MODE=check; shift ;; --remove) MODE=remove; shift ;; --join) JOIN=1; shift; if [ $# -gt 0 ] && [ "${1#-}" = "$1" ]; then JOIN_CODE="$1"; shift; fi ;; --tailscale) TAILSCALE=1; shift ;; --ssh-port) SSH_PORT="${2:?--ssh-port needs a number}"; shift 2 ;; --pair-port) PAIR_PORT="${2:?--pair-port needs a number}"; shift 2 ;; --keep-packages) KEEP_PACKAGES=1; shift ;; --dry-run) DRY=1; shift ;; --yes|-y) YES=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "setup-linux.sh: unknown option $1 (see --help)" >&2; exit 2 ;; esac done for n in "$SSH_PORT" "$PAIR_PORT"; do case "$n" in ""|*[!0-9]*) [ -z "$n" ] || { echo "setup-linux.sh: a port is a number: $n" >&2; exit 2; } ;; esac done if [ "$MODE" = remove ] && [ "$JOIN" = 1 ]; then echo "setup-linux.sh: --remove and --join do not go together" >&2; exit 2; fi say() { printf '%s\n' "$*"; } # How to run this script again, for the hints: its own path, or the piped form when it came through curl (then $0 is bash). if [ -f "$0" ] && [ "${0##*/}" = setup-linux.sh ]; then SELF="sudo bash $0"; else SELF="curl -fsSL ${DIY_SITE:-https://install.vibedout.app}/worker/setup-linux.sh | sudo bash -s --"; fi step() { printf '\n== %s\n' "$*"; } warn() { printf 'warning: %s\n' "$*" >&2; } die() { printf 'setup-linux.sh: %s\n' "$*" >&2; exit 1; } run() { if [ "$DRY" = 1 ]; then printf 'would run: %s\n' "$*"; else "$@"; fi; } if [ -z "$ROOT" ] && [ "$DRY" = 0 ] && [ "$(id -u)" != 0 ]; then die "run it as root: $SELF${ARGS:+ $ARGS}" fi # ---- the machine --------------------------------------------------------------------------------------------------------- osr="$(R /etc/os-release)" [ -r "$osr" ] || die "no /etc/os-release: this script knows Ubuntu, Debian and Fedora" OS_ID="$(sed -n 's/^ID=//p' "$osr" | tr -d '"' | head -n1)" OS_LIKE="$(sed -n 's/^ID_LIKE=//p' "$osr" | tr -d '"' | head -n1)" OS_VER="$(sed -n 's/^VERSION_ID=//p' "$osr" | tr -d '"' | head -n1)" OS_NAME="$(sed -n 's/^PRETTY_NAME=//p' "$osr" | tr -d '"' | head -n1)" case "$OS_ID $OS_LIKE" in *ubuntu*|*debian*) FAMILY=debian ;; *fedora*) FAMILY=fedora ;; *) die "$OS_NAME is not one this script knows (Ubuntu 22.04+, Debian 12+, Fedora 39+)" ;; esac major="${OS_VER%%.*}"; case "$major" in ""|*[!0-9]*) major=0 ;; esac case "$OS_ID" in ubuntu) [ "$major" -ge 22 ] || die "Ubuntu $OS_VER is too old: 22.04 or newer (WebKitGTK 4.1)" ;; debian) [ "$major" -ge 12 ] || die "Debian $OS_VER is too old: 12 or newer (WebKitGTK 4.1)" ;; fedora) [ "$major" -ge 39 ] || die "Fedora $OS_VER is too old: 39 or newer" ;; esac case "$(uname -m)" in x86_64|amd64) ARCH=x86_64; NARCH=x64; NODE_SHA="$NODE_SHA256_X64"; ZARCH=x86_64-linux; ZIG_SHA="$ZIG_SHA256_X64"; TRIPLE=x86_64-unknown-linux-gnu ;; aarch64|arm64) ARCH=aarch64; NARCH=arm64; NODE_SHA="$NODE_SHA256_ARM64"; ZARCH=aarch64-linux; ZIG_SHA="$ZIG_SHA256_ARM64"; TRIPLE=aarch64-unknown-linux-gnu ;; *) die "$(uname -m) is not one this script knows (x86_64, aarch64)" ;; esac CORES="$(nproc 2>/dev/null || echo 1)" MEM_GB="$(awk '/^MemTotal:/ { printf "%d", $2 / 1048576 + 0.5 }' "$(R /proc/meminfo)" 2>/dev/null || echo 0)" case "$MEM_GB" in ""|*[!0-9]*) MEM_GB=0 ;; esac # The lane's caps from this machine (DIY's heavy.sh reads them): keep an eighth of the memory (at least 2 GB) for the system; wait for three # quarters of the cap before a job starts; a DIY compile peaks near 4 GB a job, so the jobs follow the memory, never more than the cores. LANE_MEM=$((MEM_GB - (MEM_GB / 8 > 2 ? MEM_GB / 8 : 2))); [ "$LANE_MEM" -ge 1 ] || LANE_MEM=1 LANE_MIN_AVAIL=$((LANE_MEM * 3 / 4)); [ "$LANE_MIN_AVAIL" -ge 1 ] || LANE_MIN_AVAIL=1 LANE_JOBS=$(((MEM_GB - 2) / 4)); [ "$LANE_JOBS" -ge 1 ] || LANE_JOBS=1; [ "$LANE_JOBS" -le "$CORES" ] || LANE_JOBS="$CORES" STATE_DIR="$(R /var/lib/diy-worker-setup)" STATE="$STATE_DIR/state" OPT="$(R /opt/diy-worker)" SSHD_DROPIN="$(R /etc/ssh/sshd_config.d/50-diy-worker.conf)" SSHD_PORT_DROPIN="$(R /etc/ssh/sshd_config.d/40-diy-worker-port.conf)" state_has() { [ -f "$STATE" ] && grep -qxF "$1" "$STATE"; } # made : the script is about to create it; --remove takes away only what is recorded so (51.40 review 1) made() { [ -e "$1" ] || state_add "made=${1#"$ROOT"}"; } state_add() { [ "$DRY" = 1 ] && return 0; mkdir -p "$STATE_DIR"; chmod 700 "$STATE_DIR"; state_has "$1" || printf '%s\n' "$1" >> "$STATE"; } user_home() { getent passwd "$WUSER" | cut -d: -f6; } user_exists() { getent passwd "$WUSER" >/dev/null 2>&1; } # in the test seam the home is under the root like everything else WHOME_RAW="/home/$WUSER" WHOME() { local h; h="$(user_home 2>/dev/null)"; [ -n "$h" ] || h="$WHOME_RAW"; R "$h"; } as_user() { run runuser -u "$WUSER" -- env HOME="$(WHOME)" "$@"; } # ---- packages ------------------------------------------------------------------------------------------------------------ if [ "$FAMILY" = debian ]; then PACKAGES=(build-essential clang mold pkg-config git curl ca-certificates file xz-utils unzip openssh-server openssl python3 dbus-user-session libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev libssl-dev libxdo-dev libudev-dev) pkg_installed() { dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q 'install ok installed'; } pkg_install() { run env DEBIAN_FRONTEND=noninteractive apt-get update -q && run env DEBIAN_FRONTEND=noninteractive apt-get install -y -q --no-install-recommends "$@"; } pkg_remove() { run env DEBIAN_FRONTEND=noninteractive apt-get remove -y -q "$@"; } SSH_UNIT=ssh else PACKAGES=(gcc gcc-c++ make clang mold pkgconf-pkg-config git curl ca-certificates file xz unzip openssh-server openssl python3 webkit2gtk4.1-devel gtk3-devel libappindicator-gtk3-devel librsvg2-devel openssl-devel libxdo-devel systemd-devel) pkg_installed() { rpm -q "$1" >/dev/null 2>&1; } pkg_install() { run dnf install -y -q "$@"; } pkg_remove() { run dnf remove -y -q "$@"; } SSH_UNIT=sshd fi missing_packages() { local p; for p in "${PACKAGES[@]}"; do pkg_installed "$p" || printf '%s\n' "$p"; done; } CHROME="$(R /opt/google/chrome/chrome)" chrome_ok() { [ -x "$CHROME" ] || { [ "$ARCH" = aarch64 ] && command -v chromium >/dev/null 2>&1; }; } # ---- downloads ----------------------------------------------------------------------------------------------------------- sha_of() { sha256sum "$1" | cut -d' ' -f1; } # fetch URL FILE [SHA256]: a download that does not match is deleted and the script stops fetch() { local url="$1" out="$2" want="${3:-}" got run curl -fsSL --retry 3 --proto '=https' -o "$out" "$url" || die "could not download $url" [ "$DRY" = 1 ] && return 0 if [ -n "$want" ]; then got="$(sha_of "$out")" if [ "$got" != "$want" ]; then rm -f "$out"; die "the sha256 of $url is $got, expected $want. Nothing was installed from it."; fi fi } TMPW="" # the run's temp folder, made on first use in this shell (never in a $(...) subshell, where it would be made again and never removed) tmpw() { [ -n "$TMPW" ] || TMPW="$(mktemp -d)"; } PAIR_FW="" # the pairing port, open in an active firewall only while --join waits (51.40 review 1) close_pair_port() { case "$PAIR_FW" in ufw) ufw delete allow "$PAIR_PORT/tcp" >/dev/null 2>&1 || true ;; firewalld) firewall-cmd -q --remove-port="$PAIR_PORT/tcp" >/dev/null 2>&1 || true ;; esac PAIR_FW="" } cleanup() { close_pair_port; [ -z "$TMPW" ] || rm -rf "$TMPW"; } trap cleanup EXIT NODE_DIR="$OPT/node-v$NODE_VERSION-linux-$NARCH" ZIG_DIR="$OPT/zig-$ZARCH-$ZIG_VERSION" node_ok() { [ -x "$NODE_DIR/bin/node" ] && [ "$(readlink "$OPT/node" 2>/dev/null)" = "$NODE_DIR" ]; } # pnpm is a Node script (#!/usr/bin/env node): it runs with this Node first on PATH (root's PATH has none; found on a real VM, 51.40-T25) pnpm_ok() { [ -x "$NODE_DIR/bin/pnpm" ] && [ "$(PATH="$NODE_DIR/bin:$PATH" "$NODE_DIR/bin/pnpm" --version 2>/dev/null)" = "$PNPM_VERSION" ]; } zig_ok() { [ -x "$ZIG_DIR/zig" ] && [ "$(readlink "$OPT/zig" 2>/dev/null)" = "$ZIG_DIR" ]; } rust_ok() { local rc; rc="$(WHOME)/.cargo/bin/rustc"; [ -x "$rc" ] && as_user "$rc" --version 2>/dev/null | grep -q "^rustc $RUST_VERSION "; } linger_ok() { [ -e "$(R /var/lib/systemd/linger/$WUSER)" ]; } envfile() { printf '%s/.config/diy-worker/env' "$(WHOME)"; } lanefile() { printf '%s/.config/diy-worker/lane.env' "$(WHOME)"; } cargocfg() { printf '%s/.cargo/config.toml' "$(WHOME)"; } lane_ok() { [ -f "$(lanefile)" ] && grep -qx "HEAVY_MEM=${LANE_MEM}G" "$(lanefile)"; } work_ok() { [ -d "$(WHOME)/work/seats" ] && [ -d "$(WHOME)/work/repos" ]; } sshd_dropin_ok() { [ -f "$SSHD_DROPIN" ] && { [ -z "$SSH_PORT" ] || grep -qx "Port $SSH_PORT" "$SSHD_PORT_DROPIN" 2>/dev/null; }; } sshd_running() { systemctl is-active --quiet "$SSH_UNIT" 2>/dev/null || systemctl is-active --quiet "$SSH_UNIT.socket" 2>/dev/null; } joined() { [ -s "$(WHOME)/.ssh/authorized_keys" ] && grep -q 'diy-worker-pair' "$(WHOME)/.ssh/authorized_keys"; } tailscale_ip() { command -v tailscale >/dev/null 2>&1 && tailscale ip -4 2>/dev/null | head -n1; } # ---- --check -------------------------------------------------------------------------------------------------------------- bad=0 ok() { printf ' [ok] %-12s %s\n' "$1" "$2"; } no() { printf ' [missing] %-12s %s\n fix: %s\n' "$1" "$2" "$3"; bad=1; } info() { printf ' [note] %-12s %s\n' "$1" "$2"; } # item item() { if "$1"; then ok "$2" "$3"; else no "$2" "$4" "$5"; fi; } mem_ok() { [ "$MEM_GB" -ge 8 ]; } pkgs_ok() { [ -z "$(missing_packages)" ]; } check() { bad=0 say "DIY build machine on $OS_NAME ($ARCH): $CORES cores, ${MEM_GB} GB memory" if mem_ok; then ok memory "${MEM_GB} GB"; else info memory "${MEM_GB} GB: a DIY library build wants 12 GB or more; small builds and tests still run"; fi local free_gb; free_gb="$(df -Pk "$(R /home)" 2>/dev/null | awk 'NR==2 { printf "%d", $4 / 1048576 }')" if [ "${free_gb:-0}" -ge 40 ] 2>/dev/null; then ok disk "${free_gb} GB free under /home"; else info disk "${free_gb:-?} GB free under /home: a DIY build folder takes 20 to 30 GB per seat"; fi item pkgs_ok packages "${#PACKAGES[@]} system packages" "not installed: $(missing_packages | tr '\n' ' ')" "$SELF" item chrome_ok chrome "${CHROME#"$ROOT"}" "no Chrome at /opt/google/chrome/chrome" "$SELF" item user_exists user "$WUSER (home ${WHOME_RAW})" "no $WUSER user" "$SELF" item linger_ok linger "$WUSER keeps a systemd user session (its lane's memory caps)" "no lingering for $WUSER" "sudo loginctl enable-linger $WUSER" item rust_ok rust "rustc $RUST_VERSION for $WUSER" "no rustc $RUST_VERSION for $WUSER" "$SELF" item node_ok node "Node $NODE_VERSION in /opt/diy-worker" "no Node $NODE_VERSION in /opt/diy-worker" "$SELF" item pnpm_ok pnpm "pnpm $PNPM_VERSION" "no pnpm $PNPM_VERSION" "$SELF" item zig_ok zig "Zig $ZIG_VERSION in /opt/diy-worker" "no Zig $ZIG_VERSION in /opt/diy-worker" "$SELF" item lane_ok lane "memory cap ${LANE_MEM}G, waits for ${LANE_MIN_AVAIL} GB, ${LANE_JOBS} cargo jobs" "no lane settings for this machine's memory" "$SELF" item work_ok work "/home/$WUSER/work" "no work folder" "$SELF" item sshd_dropin_ok ssh-config "$WUSER signs in by key only${SSH_PORT:+, port $SSH_PORT}" "no sshd settings for $WUSER" "$SELF${SSH_PORT:+ --ssh-port $SSH_PORT}" item sshd_running sshd "running ($SSH_UNIT)" "sshd is not running" "sudo systemctl enable --now $SSH_UNIT" item joined joined "a DIY's key is in /home/$WUSER/.ssh/authorized_keys" "no DIY has joined this machine yet" "on your DIY: diy worker add ; here: $SELF --join" local ts; ts="$(tailscale_ip || true)" if [ -n "$ts" ]; then ok tailnet "$ts (your DIY reaches this machine there)" elif command -v tailscale >/dev/null 2>&1; then info tailnet "Tailscale is installed and not signed in: sudo tailscale up" else info tailnet "no Tailscale: your DIY reaches this machine on the local network, or install it with $SELF --tailscale"; fi if [ "$bad" = 0 ]; then say "Everything is there."; else say "Something is missing: the fix is under each line."; fi return "$bad" } # ---- install --------------------------------------------------------------------------------------------------------------- install_packages() { step "system packages" local m; mapfile -t m < <(missing_packages) if [ "${#m[@]}" = 0 ]; then say "all ${#PACKAGES[@]} there"; return 0; fi say "installing: ${m[*]}" pkg_install "${m[@]}" || die "the package manager failed (above); run again once it is fixed" local p; for p in "${m[@]}"; do state_add "pkg=$p"; done } install_chrome() { step "Chrome" if chrome_ok; then say "there"; return 0; fi if [ "$ARCH" = aarch64 ]; then if [ "$FAMILY" = debian ] && [ "$OS_ID" = ubuntu ]; then warn "no Chrome for arm64 Linux and Ubuntu's Chromium is a snap: browser walks need BENCH_CHROME set to a browser you install"; return 0; fi pkg_install chromium || die "could not install Chromium"; state_add "pkg=chromium"; return 0 fi if [ "$FAMILY" = debian ]; then local deb; tmpw; deb="$TMPW/chrome.deb" fetch https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb "$deb" run chmod 644 "$deb" pkg_install "$deb" || die "could not install Chrome" else pkg_install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm || die "could not install Chrome" fi state_add "pkg=google-chrome-stable" } make_user() { step "the $WUSER user" if user_exists; then say "there"; else run useradd --create-home --home-dir "$WHOME_RAW" --shell /bin/bash --comment "DIY build machine" "$WUSER" || die "could not make the $WUSER user" run passwd -l "$WUSER" >/dev/null || true state_add "created-user=1" fi if ! linger_ok; then run loginctl enable-linger "$WUSER" || warn "could not turn on lingering: jobs run without memory caps until it is on"; fi } install_node() { step "Node $NODE_VERSION and pnpm $PNPM_VERSION" made "$OPT"; run mkdir -p "$OPT" if node_ok; then say "Node there"; else local tar; tmpw; tar="$TMPW/node.tar.xz" fetch "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-$NARCH.tar.xz" "$tar" "$NODE_SHA" run rm -rf "$NODE_DIR" run tar -C "$OPT" -xJf "$tar" run ln -sfn "$NODE_DIR" "$OPT/node" fi if pnpm_ok; then say "pnpm there"; else run env PATH="$NODE_DIR/bin:$PATH" "$NODE_DIR/bin/npm" install -g --prefix "$NODE_DIR" --no-fund --no-audit "pnpm@$PNPM_VERSION" || die "could not install pnpm" fi } install_zig() { step "Zig $ZIG_VERSION" if zig_ok; then say "there"; return 0; fi local tar; tmpw; tar="$TMPW/zig.tar.xz" fetch "https://ziglang.org/download/$ZIG_VERSION/zig-$ZARCH-$ZIG_VERSION.tar.xz" "$tar" "$ZIG_SHA" made "$OPT"; run mkdir -p "$OPT" run rm -rf "$ZIG_DIR" run tar -C "$OPT" -xJf "$tar" run ln -sfn "$ZIG_DIR" "$OPT/zig" } install_rust() { step "Rust $RUST_VERSION for $WUSER" if rust_ok; then say "there"; return 0; fi local rup; rup="$(WHOME)/.cargo/bin/rustup" if [ -x "$rup" ]; then as_user "$rup" toolchain install "$RUST_VERSION" --profile minimal -c clippy -c rustfmt || die "rustup could not install $RUST_VERSION" as_user "$rup" default "$RUST_VERSION" || die "rustup could not make $RUST_VERSION the default" return 0 fi local init want dl; tmpw; dl="$TMPW" fetch "https://static.rust-lang.org/rustup/dist/$TRIPLE/rustup-init.sha256" "$dl/rustup-init.sha256" want=""; [ "$DRY" = 1 ] || want="$(cut -d' ' -f1 "$dl/rustup-init.sha256")" fetch "https://static.rust-lang.org/rustup/dist/$TRIPLE/rustup-init" "$dl/rustup-init" "$want" # rustup-init knows what it is by its file name: it must be called rustup-init (any other name is taken for a proxy) local grp; grp="$(id -gn "$WUSER" 2>/dev/null || echo "$WUSER")" init="$(WHOME)/.diy-worker-setup/rustup-init" run install -d -o "$WUSER" -g "$grp" -m 0700 "$(dirname "$init")" run install -o "$WUSER" -g "$grp" -m 0755 "$dl/rustup-init" "$init" as_user "$init" -y --no-modify-path --profile minimal --default-toolchain "$RUST_VERSION" -c clippy -c rustfmt || { run rm -rf "$(dirname "$init")"; die "rustup-init failed (above)"; } run rm -rf "$(dirname "$init")" } write_as_user() { # file mode: content from stdin, owned by the user local f="$1" mode="$2" tmp if [ "$DRY" = 1 ]; then printf 'would write %s\n' "$f"; cat >/dev/null; return 0; fi mkdir -p "$(dirname "$f")" # written in a folder of root's and put in place by install, which replaces what is there (a link a job planted is not followed) tmpw; tmp="$TMPW/write.$$"; cat > "$tmp" # the same content and mode: nothing to do (a second run changes nothing) if [ -f "$f" ] && [ ! -L "$f" ] && cmp -s "$tmp" "$f" && [ "$(stat -c %a "$f")" = "$mode" ]; then rm -f "$tmp"; return 0; fi install -o "$WUSER" -g "$(id -gn "$WUSER" 2>/dev/null || echo "$WUSER")" -m "$mode" "$tmp" "$f"; rm -f "$tmp" chown "$WUSER:$(id -gn "$WUSER" 2>/dev/null || echo "$WUSER")" "$(dirname "$f")" } write_lane() { step "the lane: ${LANE_MEM}G cap, waits for ${LANE_MIN_AVAIL} GB, ${LANE_JOBS} jobs" local h; h="$(WHOME)" run mkdir -p "$h/work/seats" "$h/work/repos" run chown -R "$WUSER:$(id -gn "$WUSER" 2>/dev/null || echo "$WUSER")" "$h/work" run chmod 700 "$h/work" write_as_user "$(lanefile)" 644 </dev/null; then { printf '%s\n' "$line"; cat "$rc" 2>/dev/null || true; } > "$rc.tmp.$$" && mv "$rc.tmp.$$" "$rc" chown "$WUSER:$(id -gn "$WUSER" 2>/dev/null || echo "$WUSER")" "$rc" fi } setup_sshd() { step "sshd: $WUSER by key only${SSH_PORT:+, port $SSH_PORT}" if [ "$DRY" = 0 ]; then mkdir -p "$(dirname "$SSHD_DROPIN")" made "$SSHD_DROPIN" cat > "$SSHD_DROPIN" < "$SSHD_PORT_DROPIN"; state_add "ssh-port=$SSH_PORT"; fi # sshd -t needs its privilege separation folder, which only the running service makes (Ubuntu 24.04 starts sshd on demand): # make it as the service would, else a machine whose sshd has not run yet refuses good settings (found on a real VM, 51.40-T25) [ -d "$(R /run/sshd)" ] || install -d -m 0755 "$(R /run/sshd)" if ! sshd -t 2>/dev/null; then local why; why="$(sshd -t 2>&1 || true)" rm -f "$SSHD_DROPIN" "$SSHD_PORT_DROPIN" die "sshd refused the settings, so they were taken out again: $why" fi fi run systemctl enable --now "$SSH_UNIT" >/dev/null 2>&1 || run systemctl enable --now "$SSH_UNIT.socket" >/dev/null 2>&1 || warn "could not start sshd ($SSH_UNIT)" if systemctl is-enabled --quiet "$SSH_UNIT.socket" 2>/dev/null; then run systemctl daemon-reload; run systemctl restart "$SSH_UNIT.socket" || true fi run systemctl reload-or-restart "$SSH_UNIT" 2>/dev/null || true if [ -n "$SSH_PORT" ]; then if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q 'Status: active'; then run ufw allow "$SSH_PORT/tcp" >/dev/null && state_add "ufw=$SSH_PORT"; fi if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then run firewall-cmd -q --permanent --add-port="$SSH_PORT/tcp" && run firewall-cmd -q --reload && state_add "firewalld=$SSH_PORT" fi fi } setup_tailscale() { step "Tailscale" if ! command -v tailscale >/dev/null 2>&1; then local s; tmpw; s="$TMPW/tailscale-install.sh" fetch https://tailscale.com/install.sh "$s" run sh "$s" || die "Tailscale's installer failed (above)" fi if [ -n "$(tailscale_ip || true)" ]; then say "signed in: $(tailscale_ip)"; return 0; fi say "Sign in to your own tailnet: Tailscale prints a link; open it on any device and approve this machine." run tailscale up || die "tailscale up did not finish; run sudo tailscale up yourself, then this script again" } # ---- --join (T22) ------------------------------------------------------------------------------------------------------------ # The pairing listener: the protocol is tools/cli/worker.mjs's (both sides are tested together in tools/worker/test). The worker never # answers with anything a guesser could test a code against until the DIY has proved it knows the code. pair_listener() { cat <<'NODE' const net = require("node:net"), crypto = require("node:crypto"), fs = require("node:fs"); const V = "diy-worker-pair-v1"; const code = String(process.env.DIY_PAIR_CODE || "").toUpperCase().replace(/[^0-9A-Z]/g, ""); const port = Number(process.env.DIY_PAIR_PORT), wait = Number(process.env.DIY_PAIR_WAIT) * 1000; const hostkey = fs.readFileSync(process.env.DIY_PAIR_HOSTKEY, "utf8").trim().split(/\s+/).slice(0, 2).join(" "); const facts = fs.readFileSync(process.env.DIY_PAIR_FACTS, "utf8").trim(); const K = crypto.createHmac("sha256", V).update(code).digest(); const mac = (s) => crypto.createHmac("sha256", K).update(s).digest("hex"); const same = (a, b) => typeof a === "string" && a.length === b.length && crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)); // A wrong code slows its sender (1, 2, 4 ... 60 s, by address) and never ends the listener: anyone who can reach the port could // otherwise cancel the pairing (51.40 review 1). The listener's life is the ten minutes, nothing else. const slow = new Map(); let done = false; const server = net.createServer((sock) => { const who0 = sock.remoteAddress || ""; const s0 = slow.get(who0); if (s0 && Date.now() < s0.until) { sock.destroy(); return; } sock.setTimeout(10000, () => sock.destroy()); let buf = "", step = 0, nL = "", nW = crypto.randomBytes(16).toString("hex"); const send = (o) => sock.write(JSON.stringify(o) + "\n"); sock.on("error", () => {}); sock.on("data", (d) => { buf += d; if (buf.length > 16384) return sock.destroy(); let i; while ((i = buf.indexOf("\n")) >= 0) { const line = buf.slice(0, i); buf = buf.slice(i + 1); let m; try { m = JSON.parse(line); } catch { return sock.destroy(); } if (step === 0 && m.t === "hello" && m.v === 1 && /^[0-9a-f]{32}$/.test(m.n)) { nL = m.n; send({ t: "hello", v: 1, n: nW }); step = 1; continue; } if (step === 1 && m.t === "key") { const pub = String(m.pubkey || ""), who = String(m.laptop || ""); const ok = /^ssh-ed25519 [A-Za-z0-9+/]{68}$/.test(pub) && /^[A-Za-z0-9._-]{1,64}$/.test(who) && same(m.mac, mac(`${V}|L|${nL}|${nW}|${pub}|${who}`)); if (!ok) { const s = slow.get(who0) || { n: 0, until: 0 }; s.n++; s.until = Date.now() + Math.min(60000, 1000 * 2 ** (s.n - 1)); slow.set(who0, s); send({ t: "no", why: "wrong code" }); sock.end(); process.stderr.write(`a wrong code from ${who0} (${s.n}): it waits ${Math.round((s.until - Date.now()) / 1000)} s before it may try again\n`); return; } send({ t: "facts", hostkey, facts, mac: mac(`${V}|W|${nL}|${nW}|${pub}|${hostkey}|${facts}`) }); done = true; process.stdout.write(JSON.stringify({ pubkey: pub, laptop: who, peer: sock.remoteAddress }) + "\n", () => { sock.end(); server.close(); setTimeout(() => process.exit(0), 300); }); return; } return sock.destroy(); } }); }); server.on("error", (e) => { process.stderr.write(`cannot listen on port ${port}: ${e.message}\n`); process.exit(1); }); server.listen(port, process.env.DIY_PAIR_BIND || "0.0.0.0"); setTimeout(() => { if (!done) { process.stderr.write("nobody came\n"); process.exit(3); } }, wait); NODE } json_str() { # a JSON string of $1 (the facts are plain words: letters, digits, dots, dashes, spaces, colons, slashes) printf '"%s"' "$(printf '%s' "$1" | tr -cd 'A-Za-z0-9 ._:/@,+()-' | cut -c1-120)" } do_join() { step "join this machine to your DIY" user_exists || die "no $WUSER user: run $SELF first" local node="$OPT/node/bin/node"; [ -x "$node" ] || node="$(command -v node || true)" [ -n "$node" ] || die "no Node to run the pairing with: run $SELF first" local hk; hk="$(R /etc/ssh/ssh_host_ed25519_key.pub)" [ -r "$hk" ] || die "no ed25519 host key at /etc/ssh/ssh_host_ed25519_key.pub: sudo ssh-keygen -A, then again" if [ -z "$JOIN_CODE" ]; then if [ -r /dev/tty ] && [ -z "$ROOT" ]; then printf 'The code your DIY shows (diy worker add): ' > /dev/tty; read -r JOIN_CODE < /dev/tty else die "no code: --join CODE"; fi fi local norm; norm="$(printf '%s' "$JOIN_CODE" | tr '[:lower:]' '[:upper:]' | tr -cd '0-9A-Z')" [ "${#norm}" = 12 ] || die "a code is 12 letters and digits, like ABCD-EFGH-JKMN (you typed ${#norm})" local free_gb ts addrs facts f free_gb="$(df -Pk "$(WHOME)" 2>/dev/null | awk 'NR==2 { printf "%d", $4 / 1048576 }')" ts="$(tailscale_ip || true)" addrs="$( (hostname -I 2>/dev/null || true) | tr ' ' '\n' | grep -v ':' | grep -v '^$' | head -n 4 | tr '\n' ' ')" facts="{\"hostname\":$(json_str "$(hostname -s 2>/dev/null || hostname)"),\"user\":$(json_str "$WUSER"),\"port\":${SSH_PORT:-22},\"cores\":$CORES,\"memory_gb\":$MEM_GB,\"disk_gb\":${free_gb:-0},\"os\":$(json_str "$OS_NAME"),\"arch\":$(json_str "$ARCH"),\"tailnet\":$(json_str "$ts"),\"addresses\":$(json_str "$addrs"),\"lane\":$(json_str "${LANE_MEM}G/${LANE_MIN_AVAIL}/${LANE_JOBS}"),\"setup\":$SETUP_VERSION}" tmpw; f="$TMPW"; printf '%s' "$facts" > "$f/facts.json"; pair_listener > "$f/pair.js" say "Waiting up to $((PAIR_WAIT / 60)) minutes on port $PAIR_PORT for your DIY (it connects to this machine by itself)." [ -n "$ts" ] && say " this machine on your tailnet: $ts" [ -n "$addrs" ] && say " on the local network: $addrs" if [ "$DRY" = 0 ]; then if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q 'Status: active'; then ufw allow "$PAIR_PORT/tcp" >/dev/null && PAIR_FW=ufw elif command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then firewall-cmd -q --add-port="$PAIR_PORT/tcp" && PAIR_FW=firewalld; fi [ -z "$PAIR_FW" ] || say " port $PAIR_PORT is open in $PAIR_FW for the pairing only: it is closed again when the pairing ends" fi local out rc=0 out="$(env DIY_PAIR_CODE="$norm" DIY_PAIR_PORT="$PAIR_PORT" DIY_PAIR_WAIT="$PAIR_WAIT" DIY_PAIR_HOSTKEY="$hk" DIY_PAIR_FACTS="$f/facts.json" \ "$node" "$f/pair.js")" || rc=$? close_pair_port case "$rc" in 0) ;; 3) say "Nobody joined in time. Check that your DIY's diy worker add is still waiting, that it can reach this machine on port $PAIR_PORT, and that the code typed here is the one it shows; then again."; exit 3 ;; *) die "the pairing stopped (above)" ;; esac local pub who pub="$(printf '%s' "$out" | sed -n 's/.*"pubkey":"\(ssh-ed25519 [A-Za-z0-9+/]*\)".*/\1/p')" who="$(printf '%s' "$out" | sed -n 's/.*"laptop":"\([A-Za-z0-9._-]*\)".*/\1/p')" [ -n "$pub" ] || die "the pairing gave no key" local ak; ak="$(WHOME)/.ssh/authorized_keys" if [ "$DRY" = 0 ]; then mkdir -p "$(dirname "$ak")"; chmod 700 "$(dirname "$ak")" touch "$ak" grep -vF "$pub" "$ak" > "$ak.tmp.$$" || true printf 'restrict %s diy-worker-pair:%s\n' "$pub" "$who" >> "$ak.tmp.$$" chmod 600 "$ak.tmp.$$"; mv "$ak.tmp.$$" "$ak" chown -R "$WUSER:$(id -gn "$WUSER" 2>/dev/null || echo "$WUSER")" "$(dirname "$ak")" fi say "Joined: the DIY on $who can now send jobs to $WUSER here. Your DIY checks the sign-in and records this machine." } # ---- --remove --------------------------------------------------------------------------------------------------------------- do_remove() { step "remove the DIY build machine" if [ "$YES" = 0 ] && [ -z "$ROOT" ] && [ -r /dev/tty ]; then printf 'This deletes the %s user with its work folder, /opt/diy-worker and the sshd settings%s. Type yes: ' "$WUSER" "$([ "$KEEP_PACKAGES" = 1 ] || echo ", and the packages this script installed")" > /dev/tty local a; read -r a < /dev/tty; [ "$a" = yes ] || { say "nothing removed"; exit 1; } fi if user_exists; then if state_has "created-user=1"; then run loginctl disable-linger "$WUSER" 2>/dev/null || true run loginctl terminate-user "$WUSER" 2>/dev/null || true # its session (lingering's systemd --user, a job) takes a moment to end, and userdel refuses a user with processes (found on a real # VM, 51.40-T25): wait for them, then stop what is left, by user id if [ "$DRY" = 0 ]; then local _; for _ in $(seq 1 30); do pgrep -u "$WUSER" >/dev/null 2>&1 || break; sleep 0.5; done if pgrep -u "$WUSER" >/dev/null 2>&1; then pkill -KILL -u "$WUSER" 2>/dev/null || true; for _ in $(seq 1 10); do pgrep -u "$WUSER" >/dev/null 2>&1 || break; sleep 0.5; done; fi fi if run userdel --remove "$WUSER" 2>/dev/null || run userdel "$WUSER"; then run rm -rf "$(R "$WHOME_RAW")" say "the $WUSER user and its folder: removed" else warn "could not delete the $WUSER user (userdel, above): it and its folder stay; run this again once it has no processes" REMOVE_FAILED=1 fi else warn "the $WUSER user was not made by this script: left alone" fi fi if state_has "made=/opt/diy-worker"; then run rm -rf "$OPT"; say "/opt/diy-worker: removed"; fi if state_has "made=${SSHD_DROPIN#"$ROOT"}" || state_has "made=${SSHD_PORT_DROPIN#"$ROOT"}"; then state_has "made=${SSHD_DROPIN#"$ROOT"}" && run rm -f "$SSHD_DROPIN" state_has "made=${SSHD_PORT_DROPIN#"$ROOT"}" && run rm -f "$SSHD_PORT_DROPIN" if systemctl is-enabled --quiet "$SSH_UNIT.socket" 2>/dev/null; then run systemctl daemon-reload; run systemctl restart "$SSH_UNIT.socket" || true; fi run systemctl reload-or-restart "$SSH_UNIT" 2>/dev/null || true say "sshd settings: removed" fi local p if [ -f "$STATE" ]; then p="$(sed -n 's/^ufw=//p' "$STATE")"; [ -z "$p" ] || run ufw delete allow "$p/tcp" >/dev/null || true p="$(sed -n 's/^firewalld=//p' "$STATE")"; [ -z "$p" ] || { run firewall-cmd -q --permanent --remove-port="$p/tcp" && run firewall-cmd -q --reload; } || true mapfile -t p < <(sed -n 's/^pkg=//p' "$STATE") if [ "${#p[@]}" -gt 0 ]; then if [ "$KEEP_PACKAGES" = 1 ]; then say "packages left installed (--keep-packages): ${p[*]}" else pkg_remove "${p[@]}" || warn "the package manager could not remove: ${p[*]}"; say "packages this script installed: removed (${p[*]})"; fi fi fi # Chrome's apt source and key only when this script installed Chrome (a Chrome of the person's own keeps its updates) if [ "$FAMILY" = debian ] && state_has "pkg=google-chrome-stable"; then run rm -f "$(R /etc/apt/sources.list.d/google-chrome.list)" "$(R /etc/apt/trusted.gpg.d/google-chrome.gpg)" fi if [ "${REMOVE_FAILED:-0}" = 1 ]; then say "Not all of it was removed (above): the record of what this script made stays, so running --remove again finishes it."; exit 1; fi run rm -rf "$STATE_DIR" say "Done. Tailscale, if you installed it, is left as it is: sudo tailscale logout signs this machine out of your tailnet." } # ---- main --------------------------------------------------------------------------------------------------------------------- case "$MODE" in check) check; exit $? ;; remove) do_remove; exit 0 ;; esac if [ "$JOIN" = 1 ] && user_exists && rust_ok && node_ok; then do_join; exit 0; fi say "DIY build machine set-up $SETUP_VERSION on $OS_NAME ($ARCH, $CORES cores, ${MEM_GB} GB)" install_packages install_chrome make_user install_node install_zig install_rust write_lane setup_sshd [ "$TAILSCALE" = 0 ] || setup_tailscale [ "$DRY" = 1 ] || state_add "version=$SETUP_VERSION" step "done" if [ "$JOIN" = 1 ]; then do_join; else say "This machine is ready. To join it to your DIY: on your DIY's computer run diy worker add and then here" say " $SELF --join" fi } main "$@" --end-of-script