zssh-select.fish

 1function zssh-select --description "Fuzzy-find or create a zmx session on a remote host"
 2    argparse 'h/help' 'install' -- $argv
 3    or return 1
 4
 5    if set -q _flag_help; or test (count $argv) -ne 1
 6        echo "Usage: zssh-select [--install] [user@]host"
 7        echo "Example: zssh-select hel1"
 8        return 0
 9    end
10
11    set -l destination $argv[1]
12
13    if not string match -qr '^[A-Za-z0-9._@:%+-]+$' -- $destination
14        echo "zssh-select: destination contains characters that cannot be safely used in the preview command" >&2
15        return 2
16    end
17
18    mkdir -p "$HOME/.ssh/controlmasters"
19
20    if set -q _flag_install
21        zmx-remote-install $destination
22        or return $status
23    else
24        zmx-remote-install --upgrade-only $destination
25        or return $status
26    end
27
28    set -l remote_list (command ssh \
29        -o ControlMaster=auto \
30        -o ControlPersist=10m \
31        -o ControlPath="$HOME/.ssh/controlmasters/%C" \
32        $destination \
33        "sh -c 'PATH=\"\$HOME/.local/bin:\$PATH\"; command -v zmx >/dev/null 2>&1 || { echo \"zssh-select: zmx is not installed on the remote host or is not on PATH; retry with zssh-select --install\" >&2; exit 127; }; zmx list 2>/dev/null'")
34    or return $status
35
36    set -l preview_command "ssh -o ControlMaster=auto -o ControlPersist=10m -o ControlPath=$HOME/.ssh/controlmasters/%C $destination 'sh -c '\''PATH=\"\$HOME/.local/bin:\$PATH\"; zmx history {1}'\'' '"
37    set -l session_name (printf '%s\n' $remote_list | __zmx_format_sessions | __zmx_choose_session --preview $preview_command)
38    or return $status
39
40    zssh $destination $session_name
41end