#!/bin/bash

RUNNING_SSH=false
CHILD_PID=$(pgrep -P $1)

[[ $(ps -p $CHILD_PID -o comm=) == "ssh" ]] && RUNNING_SSH=true

GRAND_CHILD_PID=$(pgrep -P $CHILD_PID)
[[ $? == 0 ]] && [[ $(ps -p $GRAND_CHILD_PID -o comm=) == "ssh" ]] && RUNNING_SSH=true && CHILD_PID=$GRAND_CHILD_PID


if [ $RUNNING_SSH == true ]; then
    CLIENT=$(ps -p $CHILD_PID -o args --no-headers | awk '{ print $2 }')
    PORT=$(ss -tnpa | grep ssh | grep "pid=$CHILD_PID" | awk '{ print $4 }' | grep -o '[0-9]*$')
    alacritty -e ssh $CLIENT -t "cd \"\$(readlink -e /proc/\$(cat /tmp/ssh_session_$PORT)/cwd)\"; zsh --login"
else
    if [ "$(ps -p $1 -o comm=)" == "alacritty" ]; then
        CWD=$(readlink -e /proc/$CHILD_PID/cwd)
        if [ "$CWD" != "" ]; then
            alacritty --working-directory "$CWD"
        else
            alacritty
        fi
    else
        alacritty
    fi
fi
