if [ -n "$REMOTE_PATH" ]; then
    # Fresh `s <host>` connection: the initial working directory is handed over in
    # REMOTE_PATH (an env var is the only channel that survives waypipe's command
    # transport intact — shell grouping like `cd …; exec …` does not). cd into it,
    # then unset so it does NOT leak to child shells: a lingering exported
    # REMOTE_PATH is what made every new zellij pane jump back to this same path
    # instead of inheriting the pane's own cwd.
    [ -d "$REMOTE_PATH" ] && cd "$REMOTE_PATH"
    unset REMOTE_PATH
fi

if [ -n "$PREVIOUS_SESSION_ID" ]; then
    # Spawned as a new window/terminal for an existing remote session (by the
    # niri/hyprland keybind). Inherit that session's working directory: find a
    # live shell whose SSH_SESSION_ID (carried in its environment) matches and
    # cd to its cwd. Then drop the hint so child shells don't keep jumping back.
    _best_pid=0
    _prev_cwd=""
    for _environ in /proc/[0-9]*/environ; do
        _pid=${_environ%/environ}
        _pid=${_pid#/proc/}
        # cat (not a < redirect) so unreadable/ptrace-protected environ files
        # fail quietly into the pipe instead of raising a shell error.
        if cat "$_environ" 2>/dev/null | tr '\0' '\n' | grep -Fxq "SSH_SESSION_ID=$PREVIOUS_SESSION_ID"; then
            [ "$(cat /proc/$_pid/comm 2>/dev/null)" = zsh ] || continue
            # SSH_SESSION_ID is exported, so transient `zsh -c …` subshells (prompt
            # hooks, zellij helpers) inherit it too — but they aren't real session
            # panes and often sit at /. Skip anything invoked in command mode; only
            # interactive login/pane shells should count.
            cat /proc/$_pid/cmdline 2>/dev/null | tr '\0' '\n' | grep -Fxq -- -c && continue
            _c=$(readlink -e /proc/$_pid/cwd 2>/dev/null) || continue
            # A login shell still sitting at / is a helper forked during startup
            # (e.g. p10k) that never ran the REMOTE_PATH cd, not a shell the user
            # works in. Real panes have always cd'd somewhere; skip root.
            [ "$_c" = / ] && continue
            if [ -n "$_c" ] && [ "$_pid" -gt "$_best_pid" ]; then
                _best_pid=$_pid
                _prev_cwd=$_c
            fi
        fi
    done
    [ -n "$_prev_cwd" ] && cd "$_prev_cwd"
    unset _best_pid _prev_cwd _environ _pid _c PREVIOUS_SESSION_ID
fi

function run_waypipe() {
    if [ -z "$1" ]; then
        echo "usage: run_waypipe <host>" >&2
        return 1
    fi
    local SSH_SESSION_ID=$RANDOM REMOTE_PATH
    # Map the current path relative to $HOME so it resolves to the remote user's
    # home even when the username differs (the remote shell expands $HOME while
    # parsing the command below).
    if [[ "$PWD" == "$HOME" || "$PWD" == "$HOME"/* ]]; then
        REMOTE_PATH="\$HOME${PWD#$HOME}"
    else
        REMOTE_PATH="$PWD"
    fi
    # Hand off the initial cwd and session token as a plain `env VAR=val … zsh`
    # argv. This must stay free of shell grouping/metacharacters: waypipe rejoins
    # and re-splits the command on whitespace and runs the leading word as a
    # program, so `env` (a real binary) works but `cd …; exec …` would not.
    #
    # SSH_SESSION_ID is placed in TWO environments on purpose:
    #   - the leading prefix exports it into the LOCAL waypipe/ssh process, where
    #     the niri/hyprland "duplicate window" keybind reads it out of
    #     /proc/<ssh-pid>/environ to learn which session to clone;
    #   - the `env SSH_SESSION_ID=…` sets it on the REMOTE zsh, where the scan
    #     block above locates this session's shells by matching it.
    SSH_SESSION_ID=$SSH_SESSION_ID waypipe -n ssh -t "$1" env REMOTE_PATH=\"$REMOTE_PATH\" SSH_SESSION_ID=$SSH_SESSION_ID zsh --login
}

alias s='run_waypipe'
