#!/bin/bash

#########################################################################
# This program is free software: you can redistribute it and/or modify  #
# it under the terms of the version 3 of the GNU General Public License #
# as published by the Free Software Foundation.                         #
#                                                                       #
# This program is distributed in the hope that it will be useful, but   #
# WITHOUT ANY WARRANTY; without even the implied warranty of            #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
# General Public License for more details.                              #
#                                                                       #
# You should have received a copy of the GNU General Public License     #
# along with this program. If not, see <http://www.gnu.org/licenses/>.  #
#                                                                       #
# Written by and Copyright (C) Francois Fleuret                         #
# Contact <francois@fleuret.org> for comments & bug reports             #
#########################################################################

# Kills all xterms which are running bash with no sub-process

set -e

NB_KILLED=0
NB_TOTAL=0
SHELL_NAME=bash

for ppid in $(ps h -C xterm -o pid); do
    N=0
    for pid in $(ps h --ppid $ppid -o pid,cmd | awk '{ if($2 == "'${SHELL_NAME}'") { print $1 }}'); do
        K=$(ps h --ppid $pid -o cmd,pid | wc -l)
        N=$((N+K+1))
    done
    if [[ $N == 1 ]]; then
        kill -USR2 $ppid
        NB_KILLED=$((NB_KILLED+1))
    fi
    NB_TOTAL=$((NB_TOTAL+1))
done

echo "Killed ${NB_KILLED} / ${NB_TOTAL} XTerm(s)"

