1function zs --description "Fuzzy-find or create a local or remote zmx session"
2 argparse 'h/help' 'install' -- $argv
3 or return 1
4
5 if set -q _flag_help; or test (count $argv) -gt 1
6 echo "Usage: zs [--install] [[user@]host]"
7 echo "Examples:"
8 echo " zs"
9 echo " zs hel1"
10 echo " zs --install finder-oscar.exe.xyz"
11 return 0
12 end
13
14 if test (count $argv) -eq 0
15 if set -q _flag_install
16 echo "zs: --install only applies when selecting sessions on a remote host" >&2
17 return 2
18 end
19
20 if not type -q zmx
21 echo "zs: zmx is not installed or not on PATH" >&2
22 return 127
23 end
24
25 set -l session_name (zmx list 2>/dev/null | __zmx_format_sessions | __zmx_choose_session --preview 'zmx history {1}')
26 or return $status
27
28 zmx attach $session_name
29 return $status
30 end
31
32 set -l destination $argv[1]
33
34 if not string match -qr '^[A-Za-z0-9._@:%+-]+$' -- $destination
35 echo "zs: destination contains characters that cannot be safely used in the preview command" >&2
36 return 2
37 end
38
39 mkdir -p "$HOME/.ssh/controlmasters"
40
41 if set -q _flag_install
42 zmx-remote-install $destination
43 or return $status
44 else
45 zmx-remote-install --upgrade-only $destination
46 or return $status
47 end
48
49 set -l remote_list (command ssh \
50 -o ControlMaster=auto \
51 -o ControlPersist=10m \
52 -o ControlPath="$HOME/.ssh/controlmasters/%C" \
53 $destination \
54 "sh -c 'PATH=\"\$HOME/.local/bin:\$PATH\"; command -v zmx >/dev/null 2>&1 || { echo \"zs: zmx is not installed on the remote host or is not on PATH; retry with zs --install HOST\" >&2; exit 127; }; zmx list 2>/dev/null'")
55 or return $status
56
57 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}'\'' '"
58 set -l session_name (printf '%s\n' $remote_list | __zmx_format_sessions | __zmx_choose_session --preview $preview_command)
59 or return $status
60
61 zssh $destination $session_name
62end