#!/bin/sh
set -e

# Copyright 2009 Holger Levsen (holger@layer-acht.org)
# Copyright © 2012-2013 Andreas Beckmann (anbe@debian.org)
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# 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 <https://www.gnu.org/licenses/>

#
# find processes running in deleted chroots
#


. /usr/share/piuparts/lib/read_config.sh

# outputs file age in seconds (or 0 if the file does not exist)
file_age()
{
	if [ -e "$1" ]; then
		local ctime now
		ctime=$(stat -c %Z "$1" 2>/dev/null || echo 0)
		now=$(date +%s)
		echo $(($now - $ctime))
	else
		echo "0"
	fi
}

get_config_value SLAVEROOT global slave-directory
get_config_value PIUPARTS_TMPDIR global tmpdir


STATEFILE=$SLAVEROOT/leftover_processes

# clear the statefile daily and whine again
test $(file_age $STATEFILE) -lt 86000 || rm -f $STATEFILE

OUTPUT="$(sudo ls --color=never -lad /proc/*/root 2>/dev/null | grep "$PIUPARTS_TMPDIR" | grep "(deleted)")"
if [ -z "$OUTPUT" ]; then
	rm -f $STATEFILE
elif [ "$(cat $STATEFILE 2>/dev/null)" != "$OUTPUT" ]; then
	echo "Found processes running with a deleted chroot in $PIUPARTS_TMPDIR"
	echo "This is usually because of 'FAIL: Processes are running inside chroot' which"
	echo "usually means the package violates 'must use invoke-rc.d (policy 9.3.3.2)'."
	echo
	echo "$OUTPUT"
	echo
	echo "Please cleanup manually."
	echo "Since #522918 has been fixed this should no longer happen."
	echo "$OUTPUT" > $STATEFILE
fi
