#!/usr/bin/env bash
# The script checks whether a defined number of Irssi processes are running per
# user and kills any excess instances, keeping only the oldest one(s) active.
#
# v0.1 - 2024-12-29 Initial release

# number of allowed Irssi sessions
allowed_sessions=2

for i in {1..60}; do
	declare -A irssi
	pof_irssi=$(pidof irssi)
	no_abusive=1

	# collect irssi PIDs
	for pid in $pof_irssi; do
		pid_owner=$(ps -o uname= -p $pid)
		if [ -z ${irssi[$pid_owner]} ]; then
			irssi[$pid_owner]=1
		else
			((irssi[$pid_owner]++))
		fi
	done

	# proceed with "abusive" users
	for ab_user in "${!irssi[@]}"; do
		if [ ${irssi[$ab_user]} -gt $allowed_sessions ]; then
			no_abusive=0
			pof_irssi2=$(pgrep irssi -u $ab_user)
			pid_newest=-1
			pid_time=-1
			for pid in $pof_irssi2; do
				tmp_pid_time=$(stat -c %Y /proc/$pid)
				if [ $tmp_pid_time -gt $pid_time ]; then
					pid_newest=$pid
					pid_time=$tmp_pid_time
				fi
			done

			kill $pid_newest
		fi
	done
	unset irssi

	if [ $no_abusive -eq 1 ]; then
		exit
	fi
	sleep 1
done