#!/usr/bin/env bash
#
# imath-setup.sh — sets up passwordless SSH access to the compute nodes of the
# Institute of Mathematics at UZH (I-MATH / DM3L).
#
# It creates:
#   ~/.ssh/id_imath                  a dedicated ed25519 key
#   ~/.ssh/config                    a host entry "imath" (the jump host)
#   ~/.config/imath/imath.sh         the imath command itself
#   ~/.zshrc or ~/.bashrc            one line that loads the file above
#   ~/.bashrc on the cluster         a PATH fix so that Rscript works over SSH
#
# On macOS it also installs Homebrew and XQuartz (needed by imath --visual).
#
# Usage:   ./imath-setup.sh                      asks for the username
#          ./imath-setup.sh <your-imath-username>
#          ./imath-setup.sh --no-xquartz <user>    skip the XQuartz step
#          ./imath-setup.sh --copy-key <user>      do not use the password at
#                                                  all: put the key on the
#                                                  server by hand (ThinLinc)
#          ./imath-setup.sh --show-key             show the public key and how
#                                                  to install it by hand
#          ./imath-setup.sh --uninstall
#          ./imath-setup.sh --help
#
# Logging in for the first time: the one password login this script needs
# may also ask for a second factor (TOTP code, recovery code, or a code by
# mail) -- that depends on your account and on where you connect from. The
# script does not read either of them; ssh asks for them directly. If you
# would rather avoid the password entirely, use --copy-key.
#
# Runs on macOS and Linux. On Windows use WSL or Git Bash — the file runs
# there unchanged; see the handbook for the two caveats (no connection reuse,
# X11 needs a separate X server such as VcXsrv).
#
# The script is idempotent: running it again changes nothing twice, and it is
# also how you update — every part is compared against what belongs there and
# rewritten only if it differs. Every file it touches is backed up first.
#
# Security note: connections to the compute nodes use
# StrictHostKeyChecking=accept-new, i.e. an unknown host key is trusted on
# first contact (trust on first use) and pinned afterwards. That is a
# deliberate trade-off: the alternative is a confirmation prompt for each of
# ~38 internal machines. A man-in-the-middle inside the institute network
# would not be detected at that very first contact. If you want it stricter,
# remove the option and confirm the fingerprints by hand.
#
set -euo pipefail

JUMPHOST="ssh.math.uzh.ch"
KEY="$HOME/.ssh/id_imath"
SSH_CONFIG="$HOME/.ssh/config"
CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/imath"
CONF_FILE="$CONF_DIR/imath.sh"
MARK_BEGIN="# >>> imath-setup >>>"
MARK_END="# <<< imath-setup <<<"
RMARK_BEGIN="# >>> imath-setup R-PATH >>>"
RMARK_END="# <<< imath-setup R-PATH <<<"
RESERVE_URL="https://made-fb1.math.uzh.ch"

# The institute maintains the list of its compute hosts itself. We read it from
# there instead of hard-coding names that go stale.
NODE_LIST_REMOTE="/usr/sepp/etc/compute_hosts.lst"

c_ok()   { printf '\033[32m  ok\033[0m   %s\n' "$*"; }
c_info() { printf '\033[34m  ..\033[0m   %s\n' "$*"; }
c_warn() { printf '\033[33m  !!\033[0m   %s\n' "$*"; }
c_err()  { printf '\033[31merror\033[0m %s\n' "$*" >&2; }
step()   { printf '\n\033[1m%s\033[0m\n' "$*"; }

# BSD and GNU mktemp agree on an explicit template, so always pass one.
mktmp()  { mktemp "${TMPDIR:-/tmp}/imath.XXXXXX"; }

detect_rc() {
    case "${SHELL##*/}" in
        zsh)  echo "$HOME/.zshrc" ;;
        bash) [ "$(uname -s)" = "Darwin" ] && echo "$HOME/.bash_profile" || echo "$HOME/.bashrc" ;;
        *)    echo "" ;;
    esac
}

# --------------------------------------------------------------------------
# Leftovers. Two older shapes exist in the wild:
#   1. a hand-inserted block "# ---- UZH I-MATH ---...---" without markers
#   2. a marked block that contained all ~350 function lines inline
# The second is replaced automatically (it is inside the markers); the first
# is detected and removed here.
# --------------------------------------------------------------------------
LEGACY_BEGIN="# ---- UZH I-MATH"
LEGACY_END="# ---------------------------------------------------------------------------"

legacy_cleanup() {
    local f="$1" n
    if [ -z "$f" ] || [ ! -f "$f" ]; then return 0; fi
    if grep -q "^$LEGACY_BEGIN" "$f"; then
        cp "$f" "$f.bak-imath-legacy"
        awk -v b="$LEGACY_BEGIN" -v e="$LEGACY_END" '
            index($0,b)==1 {skip=1; next}
            skip { if ($0==e) skip=0; next }
            {print}' "$f.bak-imath-legacy" > "$f"
        c_ok "removed the old unmarked imath block from $f (backup: $f.bak-imath-legacy)"
    fi
    # Anything else that is still defined outside our block we only report —
    # the script does not touch lines somebody else wrote.
    n="$(awk -v b="$MARK_BEGIN" -v e="$MARK_END" '
            index($0,b){inb=1} index($0,e){inb=0; next}
            !inb && /^(imath|gpus|upload|download|imath_refresh_nodes)\(\)/ {print NR": "$0}' "$f")"
    if [ -n "$n" ]; then
        c_warn "$f still defines these outside the imath block:"
        printf '%s\n' "$n" | sed 's/^/         /'
        c_warn "They shadow each other — please remove them by hand."
    fi
}

# Replace the block between two markers in $1 with the contents of file $2,
# appending it if there is no block yet. Returns 0 if it changed anything.
replace_block() {
    local f="$1" new="$2" b="$3" e="$4" cur tmp rc=0
    touch "$f"
    if grep -qF "$b" "$f"; then
        cur="$(mktmp)"
        awk -v b="$b" -v e="$e" 'index($0,b){keep=1} keep{print} index($0,e){keep=0}' "$f" > "$cur"
        if cmp -s "$cur" "$new"; then rc=1; else
            cp "$f" "$f.bak-imath"
            tmp="$(mktmp)"
            awk -v b="$b" -v e="$e" -v nf="$new" \
                'index($0,b){while((getline l < nf) > 0) print l; close(nf); skip=1; next}
                 skip{if (index($0,e)) skip=0; next}
                 {print}' "$f.bak-imath" > "$tmp"
            mv "$tmp" "$f"
        fi
        rm -f "$cur"
    else
        cp "$f" "$f.bak-imath" 2>/dev/null || true
        { echo; cat "$new"; } >> "$f"
    fi
    return $rc
}

# --------------------------------------------------------------------------
# Uninstall
#
# Removes exactly what this script wrote: the one-line loader in the shell
# startup file, ~/.config/imath, the marked block in ~/.ssh/config, the node
# cache, and — if the cluster is reachable — the marked PATH block in
# ~/.bashrc over there. Homebrew, XQuartz and your key stay: they are yours,
# and other things depend on them.
# --------------------------------------------------------------------------
uninstall() {
    local rc; rc="$(detect_rc)"
    step "Removing imath-setup"

    # The remote part FIRST: it needs the ssh config entry that the next
    # block deletes. The other way round the cluster is unreachable and the
    # PATH block would be left behind.
    remote_legacy_cleanup
    if ssh -o BatchMode=yes -o ConnectTimeout=10 imath true 2>/dev/null; then
        ssh -o BatchMode=yes imath "
            f=\$HOME/.bashrc
            if grep -qF '$RMARK_BEGIN' \$f 2>/dev/null; then
                cp \$f \$f.bak-imath-uninstall
                awk -v b='$RMARK_BEGIN' -v e='$RMARK_END' \
                    'index(\$0,b){skip=1} !skip{print} index(\$0,e){skip=0}' \
                    \$f.bak-imath-uninstall > \$f
                echo removed
            else
                echo none
            fi" 2>/dev/null | grep -q removed \
            && c_ok "PATH block removed from ~/.bashrc on the cluster" \
            || c_info "no PATH block on the cluster (or nothing to remove)"
    else
        c_warn "cluster not reachable — the PATH block in ~/.bashrc there stays."
        c_warn "Remove it later by hand, or run --uninstall again when online."
    fi

    for f in "$SSH_CONFIG" "$rc"; do
        if [ -z "$f" ] || [ ! -f "$f" ]; then continue; fi
        if grep -qF "$MARK_BEGIN" "$f"; then
            cp "$f" "$f.bak-imath-uninstall"
            awk -v b="$MARK_BEGIN" -v e="$MARK_END" \
                'index($0,b){skip=1} !skip{print} index($0,e){skip=0}' \
                "$f.bak-imath-uninstall" > "$f"
            c_ok "block removed from $f (backup: $f.bak-imath-uninstall)"
        else
            c_info "no block in $f"
        fi
    done
    legacy_cleanup "$rc"

    rm -f "$CONF_FILE"
    rmdir "$CONF_DIR" 2>/dev/null || true
    c_ok "$CONF_FILE removed"

    rm -rf "${XDG_CACHE_HOME:-$HOME/.cache}/imath"
    c_ok "node cache removed"
    rmdir "$HOME/.ssh/sockets" 2>/dev/null && c_ok "empty ~/.ssh/sockets removed" || true

    echo
    c_info "Left untouched on purpose:"
    c_info "  Homebrew and XQuartz — other software uses them"
    c_info "  $KEY — delete it yourself if you want it gone"
    c_info "  your public key in ~/.ssh/authorized_keys on the cluster"
    exit 0
}

[ "${1:-}" = "--uninstall" ] && uninstall

# --------------------------------------------------------------------------
# An older version of this script was sometimes run ON the cluster. It then
# wrote the whole imath command into the shared ~/.bashrc there, where every
# node loads it on every login. Take it out again whenever we can reach it.
# --------------------------------------------------------------------------
remote_legacy_cleanup() {
    ssh -o BatchMode=yes -o ConnectTimeout=10 imath true 2>/dev/null || return 0
    ssh -o BatchMode=yes imath "
        f=\$HOME/.bashrc
        grep -qF '$MARK_BEGIN' \$f 2>/dev/null || { echo none; exit 0; }
        cp \$f \$f.bak-imath-cleanup
        awk -v b='$MARK_BEGIN' -v e='$MARK_END' \
            'index(\$0,b){skip=1} !skip{print} index(\$0,e){skip=0}' \
            \$f.bak-imath-cleanup > \$f
        echo removed" 2>/dev/null | grep -q removed \
        && c_ok "removed a stray copy of the imath command from ~/.bashrc on the cluster" \
        || true
}

# --------------------------------------------------------------------------
# Getting the public key onto the server without the password
# --------------------------------------------------------------------------
# stdin -> the system clipboard. Returns 1 when there is no clipboard tool,
# but always consumes stdin so the caller does not block.
clip_copy() {
    if   command -v pbcopy  >/dev/null 2>&1; then pbcopy
    elif command -v wl-copy >/dev/null 2>&1; then wl-copy
    elif command -v xclip   >/dev/null 2>&1; then xclip -selection clipboard
    elif command -v xsel    >/dev/null 2>&1; then xsel --clipboard --input
    else cat >/dev/null; return 1
    fi
}

manual_key_help() {
    echo
    c_info "This is your PUBLIC key. It is not a secret — it is meant to be"
    c_info "handed out. The matching private key never leaves this machine."
    echo
    printf '    '; cat "$KEY.pub"
    echo
    if clip_copy < "$KEY.pub"; then
        c_ok "copied to your clipboard — you can paste it straight away"
    else
        c_warn "no clipboard tool here (pbcopy / wl-copy / xclip / xsel)."
        c_warn "Select the line above and copy it by hand."
    fi
    cat <<HOWTO

    Put it on the server, using a session you already have:

      1. Open ThinLinc (the institute's remote desktop) or any terminal that
         is already logged in on an institute machine. ThinLinc shares your
         clipboard with your own computer, so the key you just copied can be
         pasted there.
      2. In that terminal:

             mkdir -p ~/.ssh && chmod 700 ~/.ssh
             nano ~/.ssh/authorized_keys

      3. Paste the key at the end of the file. It has to stay ONE single
         line, beginning with "ssh-ed25519 " — no line break in the middle.
         In nano: paste, then Ctrl+O, Enter, Ctrl+X.
      4. Still in that terminal:

             chmod 600 ~/.ssh/authorized_keys

    Your home directory is the same on the jump host and on every compute
    node, so the key is in place everywhere at once.
HOWTO
}

manual_key_flow() {
    manual_key_help
    if [ ! -t 0 ]; then
        c_info "Run this script again once the key is in place."
        exit 1
    fi
    echo
    printf '    Press Enter once the key is in place (Ctrl+C to stop here): '
    read -r _ || true
    if ssh -o BatchMode=yes -o ConnectTimeout=10 imath true 2>/dev/null; then
        c_ok "passwordless login works now"
        return 0
    fi
    c_err "still no passwordless login."
    c_err "Check on the server:  cat ~/.ssh/authorized_keys"
    c_err "The key has to be one single line, and ~/.ssh must be mode 700."
    c_err "Then run this script again."
    exit 1
}

announce_login() {
    cat <<EOF
     The server asks you two things now, one after the other.

       1. Password:   your I-MATH password. Nothing is echoed while typing.
       2. Code:       your second factor -- when the server asks for it.
                      Coming in from inside the institute network or over
                      the UZH VPN, this step is often skipped; from
                      elsewhere it is not.

     If a code prompt appears, any of these works:
       * the 6-digit code from your authenticator app (TOTP)
       * one of your recovery codes
       * the word  email  — a code is mailed to your I-MATH address, and the
         prompt comes back so you can type that code

     If the server asks and you have no second factor yet, you get a menu:
       1. Create recovery codes
       2. Configure email codes
       3. Configure time-based one-time codes   <- TOTP, the usual choice
     Choose 3, copy the secret it prints into your authenticator app, then
     type a 6-digit code from the app. Open the app BEFORE you continue —
     the codes are only valid for 30 seconds.

     A wrong CODE is harmless: you simply get another try.
     A wrong PASSWORD is not: after 5 attempts the institute blocks your IP
     for 5 days. Rather abort with Ctrl+C and reset it at
     http://www.math.uzh.ch/my than guess.

     Neither the password nor the code passes through this script — ssh
     reads them straight from your terminal.

     No password at hand? Ctrl+C, then:  $0 --copy-key $USER_IMATH
EOF
    echo
}

# --------------------------------------------------------------------------
# Arguments
# --------------------------------------------------------------------------
WANT_XQUARTZ=1
MANUAL_KEY=0
while [ $# -gt 0 ]; do
    case "$1" in
        --no-xquartz) WANT_XQUARTZ=0; shift ;;
        --copy-key)   MANUAL_KEY=1; shift ;;
        --show-key)   SHOW_KEY=1; shift ;;
        --uninstall)  uninstall ;;
        -h|--help)    awk 'NR>1 && /^#/ {sub(/^# ?/,""); print; next} NR>1 {exit}' "$0"; exit 0 ;;
        -*)           c_err "unknown option: $1"; exit 1 ;;
        *)            break ;;
    esac
done

# --show-key needs nothing else: print the key, say how to install it, stop.
if [ "${SHOW_KEY:-0}" = 1 ]; then
    [ -f "$KEY.pub" ] || { c_err "no key yet at $KEY.pub — run the script without --show-key first."; exit 1; }
    manual_key_help
    exit 0
fi

# --------------------------------------------------------------------------
# Prerequisites. ssh-copy-id is convenient but not required — without it the
# public key is appended over a plain ssh session further down.
# --------------------------------------------------------------------------
# This belongs on your own computer. Run on an institute machine it would
# write the imath command into the shared ~/.bashrc, where every node then
# loads it on every login -- and the jump host is not needed from there
# anyway.
if [ -d /usr/sepp ]; then
    c_err "this looks like an institute machine (/usr/sepp exists)."
    c_err "imath-setup belongs on your OWN computer — there you do not need it."
    exit 1
fi

for prog in ssh ssh-keygen scp; do
    command -v "$prog" >/dev/null || { c_err "'$prog' is missing. Please install OpenSSH."; exit 1; }
done

USER_IMATH="${1:-}"
if [ -z "$USER_IMATH" ]; then
    printf 'I-MATH username (your login for %s): ' "$JUMPHOST"
    read -r USER_IMATH
fi
[ -n "$USER_IMATH" ] || { c_err "no username given."; exit 1; }
case "$USER_IMATH" in
    *[!A-Za-z0-9._-]*) c_err "'$USER_IMATH' does not look like a username."; exit 1 ;;
esac

RC="$(detect_rc)"
[ -n "$RC" ] || { c_err "unknown shell (${SHELL}). Supported: zsh, bash."; exit 1; }

step "imath-setup for user '$USER_IMATH'"
c_info "shell startup file: $RC"

# --------------------------------------------------------------------------
# 1. macOS: Homebrew + XQuartz
# --------------------------------------------------------------------------
step "1/6  Graphics stack (macOS only)"
if [ "$(uname -s)" != "Darwin" ]; then
    c_ok "Linux/WSL — X11 is already there, nothing to do"
elif [ "$WANT_XQUARTZ" = 0 ]; then
    c_info "skipped (--no-xquartz)"
elif [ -d /Applications/Utilities/XQuartz.app ] || [ -d /opt/X11 ]; then
    c_ok "XQuartz is installed"
else
    # Homebrew first — XQuartz comes from there as a cask.
    if command -v brew >/dev/null; then
        c_ok "Homebrew found"
    else
        for p in /opt/homebrew/bin/brew /usr/local/bin/brew; do
            [ -x "$p" ] && eval "$("$p" shellenv)" && break
        done
    fi
    if ! command -v brew >/dev/null; then
        c_info "Homebrew missing — installing it (takes a few minutes)."
        if [ -t 0 ]; then
            /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" \
                || c_warn "Homebrew installation aborted."
            for p in /opt/homebrew/bin/brew /usr/local/bin/brew; do
                [ -x "$p" ] && eval "$("$p" shellenv)" && break
            done
        else
            c_warn "no terminal for the prompts — please install Homebrew by hand:"
            c_warn '  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
        fi
    fi
    if command -v brew >/dev/null; then
        # The cask writes to /Applications and /Library and needs admin rights.
        # Ask for the password now rather than halfway through the install.
        c_info "XQuartz needs administrator rights."
        if [ -t 0 ] && ! sudo -n true 2>/dev/null; then
            echo "     Please enter your Mac password once (sudo)."
            sudo -v || { c_warn "no sudo — install by hand: brew install --cask xquartz"; WANT_XQUARTZ=0; }
        elif [ ! -t 0 ] && ! sudo -n true 2>/dev/null; then
            c_warn "not running in a terminal and sudo needs a password — skipping XQuartz."
            c_warn "Install it later with: brew install --cask xquartz"
            WANT_XQUARTZ=0
        fi
        if [ "$WANT_XQUARTZ" = 0 ]; then
            :
        elif brew install --cask xquartz; then
            c_ok "XQuartz installed — log out and back in once before using 'imath --visual'"
        else
            c_warn "XQuartz installation failed. Alternative: https://www.xquartz.org"
        fi
    else
        c_warn "no Homebrew, no XQuartz — 'imath --visual' will not work yet."
    fi
fi

# --------------------------------------------------------------------------
# 2. Key pair
# --------------------------------------------------------------------------
step "2/6  SSH key"
mkdir -p "$HOME/.ssh" "$HOME/.ssh/sockets"
chmod 700 "$HOME/.ssh" "$HOME/.ssh/sockets"

if [ -f "$KEY" ]; then
    c_ok "$KEY already exists"
else
    c_info "Creating an ed25519 key."
    echo "     Choose a passphrase (>15 characters). It protects the key if your"
    echo "     machine gets lost. Leaving it empty works but is weaker — the key"
    echo "     opens the institute network without asking."
    ssh-keygen -t ed25519 -f "$KEY" -C "${USER_IMATH}@imath-$(date +%Y%m)"
    c_ok "key created"
fi

# --------------------------------------------------------------------------
# 3. ~/.ssh/config
# --------------------------------------------------------------------------
step "3/6  SSH configuration"
touch "$SSH_CONFIG"; chmod 600 "$SSH_CONFIG"

DUP="$(awk -v b="$MARK_BEGIN" -v e="$MARK_END" '
          index($0,b){inb=1} index($0,e){inb=0; next}
          !inb && /^[[:space:]]*Host[[:space:]]+imath[[:space:]]*$/ {print NR}' "$SSH_CONFIG")"
if [ -n "$DUP" ]; then
    c_warn "$SSH_CONFIG has a second 'Host imath' (line $(echo "$DUP" | tr '\n' ' '))."
    c_warn "Harmless, because the first match wins — but it can go."
fi

SSH_BLOCK="$(mktmp)"
{
    echo "$MARK_BEGIN"
    echo "# Jump host of the institute. Used by the 'imath' shell function."
    echo "Host imath"
    echo "    HostName $JUMPHOST"
    echo "    User $USER_IMATH"
    echo "    IdentityFile $KEY"
    echo "    IdentitiesOnly yes"
    echo "    AddKeysToAgent yes"
    # UseKeychain exists on macOS only; elsewhere ssh aborts on it.
    [ "$(uname -s)" = "Darwin" ] && echo "    UseKeychain yes"
    echo "    ServerAliveInterval 30"
    echo "    ServerAliveCountMax 3"
    echo "    ControlMaster auto"
    echo "    ControlPath ~/.ssh/sockets/%r@%h-%p"
    echo "    ControlPersist 10m"
    echo "$MARK_END"
} > "$SSH_BLOCK"

if [ ! -s "$SSH_CONFIG" ] || ! grep -qF "$MARK_BEGIN" "$SSH_CONFIG"; then
    # The block goes to the TOP: in ssh_config the first matching setting wins,
    # so a "Host *" further up would otherwise override our IdentityFile line.
    cp "$SSH_CONFIG" "$SSH_CONFIG.bak-imath" 2>/dev/null || true
    TMP="$(mktmp)"
    { cat "$SSH_BLOCK"; echo; cat "$SSH_CONFIG"; } > "$TMP"
    mv "$TMP" "$SSH_CONFIG"; chmod 600 "$SSH_CONFIG"
    c_ok "host 'imath' added (backup: $SSH_CONFIG.bak-imath)"
elif replace_block "$SSH_CONFIG" "$SSH_BLOCK" "$MARK_BEGIN" "$MARK_END"; then
    chmod 600 "$SSH_CONFIG"
    c_ok "host 'imath' updated (backup: $SSH_CONFIG.bak-imath)"
else
    c_ok "entry in $SSH_CONFIG is up to date"
fi
rm -f "$SSH_BLOCK"

# --------------------------------------------------------------------------
# 4. The imath command
#
# The functions live in their own file. The startup file only gets a single
# line that loads it, so updating means overwriting one file and uninstalling
# means deleting one line. The file is the same text for bash and zsh; it
# picks its completion at load time.
# --------------------------------------------------------------------------
step "4/6  The imath command"

imath_body() {
cat <<'IMATH_FUNCTIONS'

IMATH_CACHE=${XDG_CACHE_HOME:-$HOME/.cache}/imath/nodes
IMATH_GPU_CACHE=${XDG_CACHE_HOME:-$HOME/.cache}/imath/gpu-nodes
IMATH_FANOUT=8        # parallel SSH connections; the jump host's default
                      # MaxStartups is 10:30:100, so stay below it

# --- building blocks -------------------------------------------------------

# Run a command on a node. Internal only — no prompts, no terminal, and
# stdin detached so that it never eats input meant for the caller.
_imath_run() {
  local h=$1; shift
  ssh -J imath -i "$IMATH_KEY" -o BatchMode=yes -o ConnectTimeout=15 \
      -o StrictHostKeyChecking=accept-new \
      -o ControlMaster=auto -o ControlPath="$HOME/.ssh/sockets/%r@%h-%p" \
      -o ControlPersist=10m \
      "$IMATH_USER@$h" "$@" < /dev/null
}

# Escape single quotes for the far side: a path like "parent's" would
# otherwise tear a remote mkdir in half.
_imath_q() {
  printf "%s" "$1" | sed "s/'/'\\\\''/g"
}

# Everything runs through the jump host, so that is the one place a strange
# network can break. Probe it and say what actually went wrong: the inner hop
# of an "ssh -J" otherwise leaves nothing but
#   Connection closed by UNKNOWN port 65535
# A shared connection left over from another network -- laptop carried from
# the institute to a hotspot -- produces exactly the same line, so drop a
# stale one and try again before giving up.
_imath_jump_complain() {
  printf '\n  The jump host ssh.math.uzh.ch is not reachable from this network.\n' >&2
  printf '  %s\n' "$1" >&2
  printf '  imath needs one outgoing SSH connection on port 22. Some phone hotspots,\n' >&2
  printf '  hotel and guest networks block it -- there only the UZH VPN gets you through.\n\n' >&2
}

_imath_jump_check() {
  local err now rc
  now=$(date +%s)
  # One user command asks several times (node list, banner, login). Probe the
  # network once and reuse the verdict -- but keep reporting a bad one.
  if [ $(( now - ${_IMATH_JUMP_TS:-0} )) -lt 30 ]; then
    [ -z "${_IMATH_JUMP_ERR:-}" ] && return 0
    _imath_jump_complain "$_IMATH_JUMP_ERR"; return 1
  fi
  err=$(ssh -o BatchMode=yes -o ConnectTimeout=10 imath true 2>&1); rc=$?
  if [ $rc -ne 0 ] && ssh -O check imath >/dev/null 2>&1; then
    ssh -O exit imath >/dev/null 2>&1          # stale shared connection
    err=$(ssh -o BatchMode=yes -o ConnectTimeout=10 imath true 2>&1); rc=$?
  fi
  if [ $rc -eq 0 ]; then _IMATH_JUMP_TS=$now; _IMATH_JUMP_ERR=""; return 0; fi
  case "$err" in
    *"Permission denied"*|*"Too many authentication failures"*|*passphrase*)
      # The network is fine, it is the key. Let the real call do the asking.
      _IMATH_JUMP_TS=$now; _IMATH_JUMP_ERR=""; return 0 ;;
  esac
  _IMATH_JUMP_TS=$now
  _IMATH_JUMP_ERR=$(printf '%s\n' "$err" | grep -v '^[[:space:]]*$' | tail -n 1)
  [ -n "$_IMATH_JUMP_ERR" ] || _IMATH_JUMP_ERR="no reason given"
  _imath_jump_complain "$_IMATH_JUMP_ERR"
  return 1
}

# Open the connection to the jump host once, so that the parallel node
# connections multiplex over it instead of racing to create the master.
_imath_warm_jumphost() {
  _imath_jump_check || return 1
  ssh -O check imath >/dev/null 2>&1 && return 0
  ssh -fN -o BatchMode=yes -o ConnectTimeout=10 imath >/dev/null 2>&1 || return 1
}

# Wait for exactly the jobs we started — a bare "wait" would also wait for
# the user's own background jobs in an interactive shell.
_imath_wait_file() {
  local p
  [ -s "$1" ] || return 0
  while read -r p; do [ -n "$p" ] && wait "$p" 2>/dev/null; done < "$1"
  : > "$1"
}

# Run one remote command on every node, at most IMATH_FANOUT at a time.
# $1 = output directory, $2 = the remote command.
_imath_fanout() {
  local d=$1 cmd=$2 h n=0
  : > "$d/.pids"
  for h in $(_imath_nodes); do
    ( _imath_run "$h" "$cmd" > "$d/$h" 2>/dev/null ) &
    echo $! >> "$d/.pids"
    n=$((n + 1))
    if [ "$n" -ge "$IMATH_FANOUT" ]; then _imath_wait_file "$d/.pids"; n=0; fi
  done
  _imath_wait_file "$d/.pids"
  rm -f "$d/.pids"
}

_imath_nodes() {
  [ -s "$IMATH_CACHE" ] || _imath_refresh >/dev/null 2>&1
  [ -s "$IMATH_CACHE" ] && cat "$IMATH_CACHE"
}

_imath_is_node() {
  _imath_nodes | grep -qx -- "$1"
}

# The node names come live from the list the institute maintains itself.
_imath_refresh() {
  _imath_jump_check || return 1
  mkdir -p "$(dirname "$IMATH_CACHE")"
  ssh -o BatchMode=yes -o ConnectTimeout=10 imath \
      "cat $IMATH_NODELIST" 2>/dev/null \
    | grep -E '^[a-z][a-z0-9]*$' | grep -vE '^exam' > "$IMATH_CACHE.tmp"
  if [ -s "$IMATH_CACHE.tmp" ]; then
    mv "$IMATH_CACHE.tmp" "$IMATH_CACHE"
    rm -f "$IMATH_GPU_CACHE"          # GPU classification has to be redone
    printf '%s nodes cached\n' "$(wc -l < "$IMATH_CACHE" | tr -d ' ')"
    _imath_setup_completion
  else
    rm -f "$IMATH_CACHE.tmp"
    echo "could not fetch the node list (connection?)" >&2
    return 1
  fi
}

# Which nodes have a card at all? Work it out once, then remember it.
_imath_find_gpu_nodes() {
  local d h
  d=$(mktemp -d "${TMPDIR:-/tmp}/imath.XXXXXX") || return 1
  _imath_warm_jumphost
  _imath_fanout "$d" 'nvidia-smi -L 2>/dev/null | grep "^GPU "'
  mkdir -p "$(dirname "$IMATH_GPU_CACHE")"
  for h in $(_imath_nodes); do [ -s "$d/$h" ] && echo "$h"; done > "$IMATH_GPU_CACHE"
  rm -rf "$d"
}

# --- imath gpus ------------------------------------------------------------

_imath_gpus() {
  [ -s "$IMATH_GPU_CACHE" ] || {
    echo "finding the GPU nodes (once, takes ~20 s)..." >&2
    _imath_find_gpu_nodes
  }
  [ -s "$IMATH_GPU_CACHE" ] || { echo "no GPU nodes found." >&2; return 1; }

  local d h n=0 col=0
  if [ -t 1 ]; then col=1; fi
  d=$(mktemp -d "${TMPDIR:-/tmp}/imath.XXXXXX") || return 1
  _imath_warm_jumphost
  : > "$d/.pids"
  for h in $(cat "$IMATH_GPU_CACHE"); do
    ( _imath_run "$h" '
        nvidia-smi --query-gpu=index,name,memory.used,memory.total,utilization.gpu \
                   --format=csv,noheader,nounits 2>/dev/null | sed "s/^/G|/"
        printf "U|"; who | cut -d" " -f1 | sort -u | tr "\n" " "; echo
      ' > "$d/$h" 2>/dev/null ) &
    echo $! >> "$d/.pids"
    n=$((n + 1))
    if [ "$n" -ge "$IMATH_FANOUT" ]; then _imath_wait_file "$d/.pids"; n=0; fi
  done
  _imath_wait_file "$d/.pids"

  printf '\n'
  if [ "$col" = 1 ]; then
    printf '\033[1m  %-10s %-24s %-12s %11s  %5s  %s\033[0m\n' \
           NODE GPU IN-USE "VRAM GB" LOAD "LOGGED IN"
  else
    printf '  %-10s %-24s %-12s %11s  %5s  %s\n' \
           NODE GPU IN-USE "VRAM GB" LOAD "LOGGED IN"
  fi
  printf '  %s\n' '--------------------------------------------------------------------------------'

  for h in $(cat "$IMATH_GPU_CACHE"); do
    if [ ! -s "$d/$h" ]; then printf '  %-10s %s\n' "$h" "(no answer)"; continue; fi
    awk -v h="$h" -v col="$col" '
      function bar(f,   i,n,s) {
        n = int(f * 10 + 0.5); s = ""
        for (i = 0; i < 10; i++) s = s (i < n ? "#" : ".")
        return "[" s "]"
      }
      function paint(f, s,   c) {
        if (col != 1) return s
        c = (f < 0.5) ? "32" : (f < 0.85 ? "33" : "31")
        return "\033[" c "m" s "\033[0m"
      }
      /^G\|/ { g[++n] = substr($0, 3) }
      /^U\|/ { users = substr($0, 3); sub(/[ \t]+$/, "", users) }
      END {
        if (n == 0) { printf "  %-10s %s\n", h, "(no answer)"; exit }
        if (users == "") users = "-"
        for (i = 1; i <= n; i++) {
          if (split(g[i], a, /, */) < 5) continue
          idx = a[1]; name = a[2]; used = a[3] + 0; tot = a[4] + 0; util = a[5] + 0
          sub(/^NVIDIA /, "", name); sub(/ Generation$/, "", name)
          if (length(name) > 22) name = substr(name, 1, 21) "."
          f = (tot > 0) ? used / tot : 0
          mem = sprintf("%.1f/%.1f", used/1024, tot/1024)
          printf "  %-10s %-24s %-12s %11s  %s  %s\n",
                 (i == 1 ? h : ""), idx " " name, paint(f, bar(f)), mem,
                 paint(util/100, sprintf("%3d %%", util)),
                 (i == 1 ? users : "")
        }
      }
    ' "$d/$h"
  done
  rm -rf "$d"
  printf '\n  Idle is not the same as free: the portal decides who may use a node,\n'
  printf '  this list only shows what is running right now.\n'
  printf '  Reserve:  %s\n\n' "$IMATH_RESERVE"
}

# --- imath upload / download ----------------------------------------------
#
# Without --tmp everything goes to your cluster home, which is the same file
# system on every node. With --tmp it goes to /tmp/<user> on ONE node: local
# scratch, fast and big, but node-local and wiped eventually.

_imath_upload() {
  local to_tmp=0 node="" dest
  if [ "${1:-}" = "--tmp" ]; then to_tmp=1; shift; fi
  if [ $# -eq 0 ]; then
    echo "imath upload [--tmp] [<node>] <path...>" >&2; return 1
  fi
  _imath_jump_check || return 1
  # The first argument is a node if there is nothing here by that name.
  if [ ! -e "$1" ] && _imath_is_node "$1"; then
    node=$1; shift
  elif [ -e "$1" ] && _imath_is_node "$1"; then
    echo "note: '$1' exists here and is also a node — uploading the local file." >&2
  fi
  if [ $# -eq 0 ]; then echo "no path given." >&2; return 1; fi
  if [ "$to_tmp" = 1 ] && [ -z "$node" ]; then
    echo "--tmp needs a node:  imath upload --tmp aroca data.csv" >&2; return 1
  fi

  # A last argument ending in a slash that does not exist here is a target
  # folder on the far side, not a source path.
  local sub="" last="" a n i
  for a in "$@"; do last=$a; done
  if [ -n "$last" ] && [ ! -e "$last" ]; then
    case "$last" in */) sub=$last ;; esac
  elif [ -n "$last" ]; then
    case "$last" in
      */) echo "note: '$last' exists here — uploading it as a source, not using it as a target." >&2 ;;
    esac
  fi
  if [ -n "$sub" ]; then
    if [ $# -lt 2 ]; then echo "no path given." >&2; return 1; fi
    n=$(($# - 1)); i=0
    while [ $i -lt $n ]; do set -- "$@" "$1"; shift; i=$((i + 1)); done
    shift
  fi

  if [ "$to_tmp" = 1 ]; then
    dest="/tmp/$IMATH_USER/$sub"
    _imath_run "$node" "mkdir -p -- '$(_imath_q "$dest")'" || return 1
    scp -r -J imath -i "$IMATH_KEY" -o StrictHostKeyChecking=accept-new \
        "$@" "$IMATH_USER@$node:$dest" && printf -- '-> %s:%s  (node-local scratch)\n' "$node" "$dest"
  elif [ -n "$node" ]; then
    # The home is shared — the node is only the way there.
    scp -r -J imath -i "$IMATH_KEY" -o StrictHostKeyChecking=accept-new \
        "$@" "$IMATH_USER@$node:~/$sub" && printf -- '-> home%s (via %s)\n' "${sub:+/$sub}" "$node"
  else
    if [ -n "$sub" ]; then
      ssh -o BatchMode=yes imath "mkdir -p -- ~/'$(_imath_q "$sub")'" 2>/dev/null
    fi
    scp -r "$@" imath:"~/$sub" && printf -- '-> home%s\n' "${sub:+/$sub}"
  fi
}

_imath_download() {
  local from_tmp=0 node="" src target
  if [ "${1:-}" = "--tmp" ]; then from_tmp=1; shift; fi
  if [ $# -eq 0 ]; then
    echo "imath download [--tmp] [<node>] <path> [target]" >&2; return 1
  fi
  _imath_jump_check || return 1
  # If a file in your home happens to be named like a node, "./" disambiguates.
  case "$1" in
    ./*) set -- "${1#./}" ${2+"$2"} ;;
      *) if _imath_is_node "$1"; then node=$1; shift; fi ;;
  esac
  if [ $# -eq 0 ]; then echo "no path given." >&2; return 1; fi
  if [ "$from_tmp" = 1 ] && [ -z "$node" ]; then
    echo "--tmp needs a node:  imath download --tmp aroca out.csv" >&2; return 1
  fi
  src=$1; shift
  target=${1:-.}

  if [ "$from_tmp" = 1 ]; then
    scp -r -J imath -i "$IMATH_KEY" -o StrictHostKeyChecking=accept-new \
        "$IMATH_USER@$node:/tmp/$IMATH_USER/$src" "$target"
  elif [ -n "$node" ]; then
    scp -r -J imath -i "$IMATH_KEY" -o StrictHostKeyChecking=accept-new \
        "$IMATH_USER@$node:$src" "$target"
  else
    case "$src" in
      /*) scp -r imath:"$src" "$target" ;;
       *) scp -r imath:"~/$src" "$target" ;;
    esac
  fi
}

# --- imath <node> ----------------------------------------------------------

_imath_banner() {
  local h=$1 who
  printf '\n  \033[1m%s\033[0m\n' "$h"
  printf '  Reserved a slot?  %s   (Compute Host / with GPU)\n' "$IMATH_RESERVE"
  who=$(_imath_run "$h" 'who | cut -d" " -f1 | sort -u | tr "\n" " "' 2>/dev/null)
  who=$(printf '%s' "$who" | sed 's/[[:space:]]*$//')
  if [ -n "$who" ]; then
    printf '  Logged in right now: %s\n\n' "$who"
  else
    printf '  Logged in right now: nobody else\n\n'
  fi
}

_imath_visual_ready() {
  [ -n "${DISPLAY:-}" ] && return 0
  if [ "$(uname -s)" = "Darwin" ]; then
    if [ ! -d /Applications/Utilities/XQuartz.app ] && [ ! -d /opt/X11 ]; then
      echo "XQuartz is missing:  brew install --cask xquartz" >&2; return 1
    fi
    pgrep -q -f XQuartz || { echo "starting XQuartz..." >&2; open -a XQuartz 2>/dev/null; }
    local i=0
    while [ $i -lt 20 ]; do
      DISPLAY=$(launchctl getenv DISPLAY 2>/dev/null); export DISPLAY
      # A freshly installed XQuartz only registers with launchd after a logout;
      # the socket, however, is there immediately.
      if [ -z "$DISPLAY" ] && [ -S /private/tmp/.X11-unix/X0 ]; then export DISPLAY=:0; fi
      [ -n "$DISPLAY" ] && break
      sleep 1; i=$((i+1))
    done
  fi
  [ -n "${DISPLAY:-}" ] || { echo "no DISPLAY (no X server running)." >&2; return 1; }
}

_imath_connect() {
  local visual=0 h
  if [ "${1:-}" = "--visual" ]; then visual=1; shift; fi
  h=${1:-}; [ -n "$h" ] || { echo "no node given." >&2; return 1; }
  shift
  # Catch typos here: otherwise ssh only says "Session open refused".
  # Fetch the list first if this is the very first call on a cold cache.
  _imath_nodes >/dev/null 2>&1
  if [ -s "$IMATH_CACHE" ] && ! _imath_is_node "$h"; then
    echo "'$h' is not in the institute's node list." >&2
    echo "see the list: imath <TAB>   ·   refresh it: imath refresh" >&2
    return 1
  fi
  if [ $# -gt 0 ]; then
    echo "imath takes no command to run — log in first, then type it there:" >&2
    echo "  imath $h" >&2
    return 1
  fi
  _imath_jump_check || return 1
  if [ "$visual" = 1 ]; then
    _imath_visual_ready || return 1
    _imath_banner "$h"
    # No shared connection here. A master opened without X11 (the banner, or an
    # earlier plain login) would be reused and the forwarding would silently
    # not happen -- that is the "Missing X server or $DISPLAY" on the node.
    ssh -Y -J imath -i "$IMATH_KEY" -o StrictHostKeyChecking=accept-new \
        -o ControlMaster=no -o ControlPath=none "$IMATH_USER@$h"
  else
    _imath_banner "$h"
    ssh -J imath -i "$IMATH_KEY" -o StrictHostKeyChecking=accept-new \
        -o ControlMaster=auto -o ControlPath="$HOME/.ssh/sockets/%r@%h-%p" \
        -o ControlPersist=10m "$IMATH_USER@$h"
  fi
}

# --- imath help ------------------------------------------------------------

_imath_help() {
cat <<'HELP'

  imath — access to the compute nodes of the I-MATH

  CONNECT
    imath <node>                    Log in to a compute node. Prints the
                                    reservation link and who else is on it.
    imath --visual <node>           Log in with X11, for graphical programs
                                    (rstudio, for example). macOS: XQuartz.
    imath <TAB>                     List of all nodes.
    imath refresh                   Fetch the node list from the institute.

  RESOURCES
    imath gpus                      All GPU nodes: card, memory in use,
                                    load, who is logged in. Idle is not the
                                    same as free — the portal decides that.

  FILES -- home is shared by every node, /tmp is not
    imath upload <path...>          into your cluster home (5 GB, backed up,
                                    visible on every node)
    imath upload <path...> <dir>/   into a subfolder of your home
    imath upload <node> <path...>   same thing, routed through that node
    imath upload --tmp <node> <p..> into /tmp/<user> on THAT node: local
                                    scratch, fast and big, node-local and
                                    wiped eventually. This is where large
                                    data sets and environments belong.

    imath download <path> [target]      out of your cluster home
    imath download <node> <p> [target]  same thing, via that node
    imath download --tmp <node> <p>     out of /tmp/<user> on that node
                                        (file named like a node? use ./name)

  OTHER
    imath help                      this overview

  More: handbook in the institute wiki, support support@math.uzh.ch

HELP
}

# --- entry point -----------------------------------------------------------

imath() {
  case "${1:-}" in
    ""|help|-h|--help)  _imath_help ;;
    refresh|--refresh)  shift; _imath_refresh ;;
    gpus)               shift; _imath_gpus "$@" ;;
    upload)             shift; _imath_upload "$@" ;;
    download)           shift; _imath_download "$@" ;;
    --visual|-Y|-X)     shift; _imath_connect --visual "$@" ;;
    -*)                 echo "unknown option: $1  (imath help)" >&2; return 1 ;;
    *)                  _imath_connect "$@" ;;
  esac
}

# --- completion, picked at load time --------------------------------------

if [ -n "${ZSH_VERSION:-}" ]; then
  _imath_setup_completion() { :; }   # zsh reads the list on every tab itself

  _imath_nodes_compadd() {
    [[ -s $IMATH_CACHE ]] || _imath_refresh >/dev/null 2>&1
    [[ -s $IMATH_CACHE ]] && compadd $(cat $IMATH_CACHE)
  }

  _imath() {
    if (( CURRENT == 2 )); then
      compadd help refresh gpus upload download --visual
      _imath_nodes_compadd
      return
    fi
    case ${words[2]} in
      --visual)          (( CURRENT == 3 )) && _imath_nodes_compadd ;;
      upload)            (( CURRENT == 3 )) && _imath_nodes_compadd
                         _files ;;
      download)          (( CURRENT == 3 )) && _imath_nodes_compadd ;;
      gpus|help|refresh) ;;
      *)                 ;;
    esac
  }
  if whence compdef >/dev/null 2>&1; then compdef _imath imath; fi
else
  # -o default falls back to filenames when the word list has no match,
  # so "imath upload <TAB>" still completes local paths.
  _imath_setup_completion() {
    [ -s "$IMATH_CACHE" ] || return 0
    complete -o default -W "help refresh gpus upload download --visual $(cat "$IMATH_CACHE")" imath
  }
  _imath_setup_completion
fi
IMATH_FUNCTIONS
}

mkdir -p "$CONF_DIR"
CONF_TMP="$(mktmp)"
{
    echo "# Generated by imath-setup.sh — do not edit, it gets overwritten."
    echo "# Loaded from your shell startup file. Uninstall: imath-setup.sh --uninstall"
    # Values are written as quoted assignments, so a home directory or user
    # name containing spaces or special characters cannot break the file.
    printf 'IMATH_USER=%s\n'     "'$(printf '%s' "$USER_IMATH" | sed "s/'/'\\\\''/g")'"
    printf 'IMATH_KEY=%s\n'      "'$(printf '%s' "$KEY" | sed "s/'/'\\\\''/g")'"
    printf 'IMATH_NODELIST=%s\n' "'$(printf '%s' "$NODE_LIST_REMOTE" | sed "s/'/'\\\\''/g")'"
    printf 'IMATH_RESERVE=%s\n'  "'$(printf '%s' "$RESERVE_URL" | sed "s/'/'\\\\''/g")'"
    imath_body
} > "$CONF_TMP"

if [ -f "$CONF_FILE" ] && cmp -s "$CONF_FILE" "$CONF_TMP"; then
    c_ok "$CONF_FILE is up to date"
    rm -f "$CONF_TMP"
else
    [ -f "$CONF_FILE" ] && cp "$CONF_FILE" "$CONF_FILE.bak-imath"
    mv "$CONF_TMP" "$CONF_FILE"; chmod 644 "$CONF_FILE"
    c_ok "$CONF_FILE written"
fi

legacy_cleanup "$RC"

RC_BLOCK="$(mktmp)"
{
    echo "$MARK_BEGIN"
    echo '# The imath command lives in its own file; this only loads it.'
    echo 'if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/imath/imath.sh" ]; then'
    echo '  . "${XDG_CONFIG_HOME:-$HOME/.config}/imath/imath.sh"'
    echo 'fi'
    echo "$MARK_END"
} > "$RC_BLOCK"

if replace_block "$RC" "$RC_BLOCK" "$MARK_BEGIN" "$MARK_END"; then
    c_ok "loader line in $RC set (backup: $RC.bak-imath)"
else
    c_ok "loader line in $RC is up to date"
fi
rm -f "$RC_BLOCK"

# --------------------------------------------------------------------------
# 5. Public key onto the server
# --------------------------------------------------------------------------
step "5/6  Copying the key to the server"
if ssh -o BatchMode=yes -o ConnectTimeout=10 imath true 2>/dev/null; then
    c_ok "passwordless login already works"
elif [ "$MANUAL_KEY" = 1 ]; then
    c_info "--copy-key: no password login, you install the key by hand."
    manual_key_flow
else
    announce_login
    KEY_OK=0
    if command -v ssh-copy-id >/dev/null; then
        # ssh-copy-id first probes with publickey only (that costs no
        # password prompt) and then logs in once to install the key. So the
        # password and the second factor are asked for exactly once.
        ssh-copy-id -i "$KEY.pub" imath && KEY_OK=1
    else
        # No ssh-copy-id (Git Bash, minimal systems): append it ourselves.
        c_info "ssh-copy-id is not installed — appending the key over ssh."
        if ssh imath "umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys" < "$KEY.pub"; then
            ssh -o BatchMode=yes imath \
                'sort -u ~/.ssh/authorized_keys -o ~/.ssh/authorized_keys' 2>/dev/null || true
            KEY_OK=1
        fi
    fi
    if [ "$KEY_OK" = 1 ]; then
        c_ok "public key installed"
    else
        # Do not just give up: the whole point of a public key is that it can
        # also be carried over by hand, through a session that already exists.
        echo
        c_warn "the password login did not go through."
        c_warn "Nothing is broken — the key just is not on the server yet."
        c_info "Second way, without any password:"
        manual_key_flow
    fi
fi

# --------------------------------------------------------------------------
# 6. R fix on the cluster
# --------------------------------------------------------------------------
step "6/6  Making Rscript usable over SSH"
remote_legacy_cleanup
# /usr/sepp/scripts/R is not R but a wrapper that wants to redirect the session
# to another machine via LDAP. In a non-interactive SSH session it dies with
# "SEPP Setup Error". So we put the real R package in front of it. The home is
# shared -> this applies on every node. The block is marked so that --uninstall
# can take it out again.
R_BLOCK="$(mktmp)"
{
    echo "$RMARK_BEGIN"
    echo '# put the real R in front of the SEPP wrapper'
    echo '_rel=$(lsb_release -rs 2>/dev/null)'
    echo '[ -z "$_rel" ] && [ -r /etc/os-release ] && _rel=$(. /etc/os-release; echo "$VERSION_ID")'
    echo '_arch=$(uname -m | sed s/x86_64/amd64/)'
    echo '_rdir=$(ls -d /usr/pack/r-*-kp/$_arch-linux-ubuntu$_rel/bin 2>/dev/null | sort -V | tail -1)'
    echo '[ -n "$_rdir" ] && [ -d "$_rdir" ] && PATH="$_rdir:$PATH"'
    echo 'unset _rdir _rel _arch'
    echo "$RMARK_END"
} > "$R_BLOCK"

# Old, unmarked versions of this block get removed first.
ssh -o BatchMode=yes imath '
    f=$HOME/.bashrc
    if grep -q "^# imath-setup R-PATH" "$f" 2>/dev/null; then
        cp "$f" "$f.bak-imath"
        awk "/^# imath-setup R-PATH/{skip=1} skip{ if (\$0 ~ /^unset _rdir/) skip=0; next } {print}" \
            "$f.bak-imath" > "$f"
    fi' 2>/dev/null || true

REMOTE_CUR="$(mktmp)"
ssh -o BatchMode=yes imath "awk -v b='$RMARK_BEGIN' -v e='$RMARK_END' \
    'index(\$0,b){keep=1} keep{print} index(\$0,e){keep=0}' ~/.bashrc" > "$REMOTE_CUR" 2>/dev/null || true

if cmp -s "$REMOTE_CUR" "$R_BLOCK"; then
    c_ok "PATH fix on the cluster is up to date"
else
    ssh -o BatchMode=yes imath "
        f=\$HOME/.bashrc
        cp \$f \$f.bak-imath 2>/dev/null || true
        if grep -qF '$RMARK_BEGIN' \$f 2>/dev/null; then
            awk -v b='$RMARK_BEGIN' -v e='$RMARK_END' \
                'index(\$0,b){skip=1} !skip{print} index(\$0,e){skip=0}' \
                \$f.bak-imath > \$f
        fi
        cat >> \$f" < "$R_BLOCK"
    c_ok "PATH fix written (~/.bashrc on the cluster, applies on every node)"
fi
rm -f "$R_BLOCK" "$REMOTE_CUR"

# --------------------------------------------------------------------------
# Final check
# --------------------------------------------------------------------------
step "Check"

if OUT="$(ssh -o BatchMode=yes -o ConnectTimeout=15 imath 'hostname' 2>&1)"; then
    c_ok "jump host reachable -> $OUT"
else
    c_err "login failed: $OUT"; exit 1
fi

# Fetch the node list and cache it right away, so that completion works from
# the first terminal on.
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/imath"
mkdir -p "$CACHE_DIR"
FIRST_NODE=""
if ssh -o BatchMode=yes imath "cat $NODE_LIST_REMOTE" 2>/dev/null \
     | grep -E '^[a-z][a-z0-9]*$' | grep -vE '^exam' > "$CACHE_DIR/nodes" \
   && [ -s "$CACHE_DIR/nodes" ]; then
    c_ok "$(wc -l < "$CACHE_DIR/nodes" | tr -d ' ') nodes fetched from the institute list"
    FIRST_NODE="$(head -1 "$CACHE_DIR/nodes")"
else
    rm -f "$CACHE_DIR/nodes"
    c_warn "the node list ($NODE_LIST_REMOTE) is not readable."
    c_warn "Completion stays empty and the node check below is skipped —"
    c_warn "no node name is guessed here. Try 'imath refresh' later."
fi

if [ -n "$FIRST_NODE" ]; then
    if OUT="$(ssh -J imath -i "$KEY" -o BatchMode=yes -o StrictHostKeyChecking=accept-new \
              -o ConnectTimeout=20 "$USER_IMATH@$FIRST_NODE" 'hostname' 2>&1)"; then
        c_ok "compute node reachable -> $OUT"
        if OUT="$(ssh -J imath -i "$KEY" -o BatchMode=yes -o ConnectTimeout=20 \
                  "$USER_IMATH@$FIRST_NODE" 'command -v Rscript' 2>&1)"; then
            case "$OUT" in
                /usr/pack/*) c_ok "Rscript usable -> $OUT" ;;
                *)           c_warn "Rscript resolves to $OUT — that is the SEPP wrapper, not R."
                             c_warn "Check the block at the end of ~/.bashrc on the cluster." ;;
            esac
        else
            c_warn "Rscript not found — R may not be installed on this node."
        fi
    else
        c_warn "node '$FIRST_NODE' is not reachable."
        c_warn "Your compute access is probably not enabled yet —"
        c_warn "a short mail to support@math.uzh.ch is enough."
    fi
fi

step "Done"
cat <<EOF
Open a new terminal, or run:  source $RC

    imath help                          all commands
    imath <TAB>                         list of all nodes
    imath aroca                         log in to a node
    imath --visual estonia0             log in with X11 (then: rstudio)
    imath gpus                          find a free card
    imath refresh                       fetch the node list again
    imath upload ~/Documents/project    into the cluster home
    imath upload --tmp aroca data.csv   onto a node's local disk
    imath download result.csv           bring it back

The command itself lives in $CONF_FILE
Undo:  $0 --uninstall
EOF
