#!/bin/sh

. /lib/functions.sh

CONFIG="sshd"
KEY_FILE="/root/.ssh/authorized_keys"

get_pid_file()
{
	local ServerName="$1"

	# this is they instances are named in sshd init file
	echo "/var/run/$CONFIG.$ServerName.pid"
}

get_session_pids()
{
	echo "$(ps -w | grep sshd | grep pts | awk '{print $1}')"
}

get_network_info()
{
	local session_pid="$1"
	local server_pid="$2"
	local session_info=""
	local ip=""
	local port=""

	# get this session's ppid
	session_ppid="$(grep PPid /proc/$session_pid/status 2>/dev/null | awk '{print $2}')"
	[ -z "$session_ppid" ] && return 1

	# get the parent of the parent (the grandparent)
	grandparent_pid="$(grep PPid /proc/$session_ppid/status 2>/dev/null | awk '{print $2}')"

	# if session's parent, or grandparent, is this server
	if [ "$session_ppid" -eq "$server_pid" ] || { [ -n "$grandparent_pid" ] && [ "$grandparent_pid" -eq "$server_pid" ]; }; then
		# The connection is usually handled by the parent process for openssh
		session_info="$(netstat -ntp 2>/dev/null | awk -v pid="$session_ppid" '$7 ~ "^"pid"/" {print $5}')"

		# If not found on parent, check the child process itself (less common for openssh)
		if [ -z "$session_info" ]; then
			session_info="$(netstat -ntp 2>/dev/null | awk -v pid="$session_pid" '$7 ~ "^"pid"/" {print $5}')"
		fi

		if [ -n "$session_info" ]; then
			ip=$(echo "$session_info" | cut -d ':' -f 1)
			port=$(echo "$session_info" | cut -d ':' -f 2)
			echo "$ip $port"
			return 0
		fi
	fi

	return 1
}
