#!/bin/sh

PROG=$(basename $0)
PIDSTOKILL=
DONTCONFIRM=0
DONTKILL=0

usage() {
    echo "${PROG}"
    echo "Kill all programs with write handles to the rootfs filesystem."
    echo " -f          Don't ask, just kill."
    echo " -l          List guilty parties, but don't kill."
    echo " -h|--help   Show this usage"
    echo " -v|--var    Do not exclude /var from search"
}

kill_cmd() {
    if [ -z "${PIDSTOKILL}" ]; then
        return;
    fi
    kill -TERM ${PIDSTOKILL}
    kill -KILL ${PIDSTOKILL}
    exit 0
}

for i; do
case "$i" in
    -f)
        shift; DONTCONFIRM=1;;
    -l)
        shift; DONTKILL=1;;
    -v|--var)
        shift; INCLUDEVAR=1;;
    -h|--help|*)
        shift; usage; exit 1;;
esac
done

cd /proc
for i in *; do
    if [ -d ${i}/fd ]; then
        fds=$(ls ${i}/fd/* 2> /dev/null)
        if [ -z "${fds}" ]; then
            continue;
        fi
        
    	for link in ${fds}; do
    	    perms=$(ls -l ${link} 2> /dev/null | cut -f 1 -d\ |grep w)
    	    if [ -z "${perms}" ]; then
    	       continue;
    	    fi
    	    file=$(readlink ${link})
    	   
    	    case "$file" in
    	    	pipe:*|socket:*|/dev*|/tmp*|inotify*|/media/internal/*)
    	            continue
    	            ;;
                /var/*)
                    [ x$INCLUDEVAR = x1 ] || continue
                    ;;
    	    	*)
    	    	    ;;
    	    esac 
            
            if [ -n "${file}" ]; then
                EXES=$(readlink /proc/${i}/exe)
                PIDSTOKILL="$PIDSTOKILL ${i}"

                echo ${EXES} ${i} ${file}
            fi
    	done
    fi
done

if [ -z "${PIDSTOKILL}" ]; then
    echo "No processes have open as writeable file handles in rootfs."
    exit 0
elif [ "$DONTKILL" -eq "1" ]; then
    exit 0;
elif [ "$DONTCONFIRM" -eq "1" ]; then
    kill_cmd; exit 0
fi

echo -n "Is it OK to kill these (y/N)?"
read response
case "${response}" in
    y|Y) kill_cmd;;
    n|N) ;;
    *) ;;
esac
