#!/bin/sh

# Copyright 2015-2023 Rivoreo
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


case "`getenforce 2> /dev/null`" in
	Enforcing|Permissive)
		mount() {
			local changed_selinux r
			[ "`getenforce 2> /dev/null`" = Enforcing ] && setenforce 0 > /dev/null 2>&1 && changed_selinux=1 || true
			/bin/mount "$@"
			r=$?
			[ -n "$changed_selinux" ] && setenforce 1 > /dev/null 2>&1 || true
			return $r
		}
		umount() {
			local changed_selinux r
			[ "`getenforce 2> /dev/null`" = Enforcing ] && setenforce 0 > /dev/null 2>&1 && changed_selinux=1 || true
			/bin/umount "$@"
			r=$?
			[ -n "$changed_selinux" ] && setenforce 1 > /dev/null 2>&1 || true
			return $r
		}
		;;
esac

set -e

trap "" HUP

mount --bind /proc/$$/task /proc/$$
proc_path=/proc/$$/$$
mount -t proc proc $proc_path
trap "umount $proc_path /proc/$$" EXIT

set +e

while true; do
	for f in /proc/*/exe; do
		[ -h "$f" ] || break
		case "`readlink $f`" in
			*/fakeroot-ng|*"/fakeroot-ng (deleted)")
				mount -t tmpfs systemd-1 -o size=0,mode=555,ro "${f%exe}" > /dev/null 2>&1
				;;
			*/sudo)
				if grep -Fq fakeroot-ng "${f%exe}cmdline"; then
					mount -t tmpfs systemd-1 -o size=0,mode=555,ro "${f%exe}" > /dev/null 2>&1
				fi
				;;
			*/script)
				if grep -Fq "          export SHELL=" "${f%exe}cmdline"; then
					mount -t tmpfs systemd-1 -o size=0,mode=555,ro "${f%exe}" > /dev/null 2>&1
				fi
				;;
		esac
	done

	while read -r line; do
		set -- $line
		[ $# != 6 ] && continue
		case "$2" in
			/proc/*/cmdline)
				# Likely to fail, no workaround available
				[ -f "${2%cmdline}stat" ] || umount "$2" > /dev/null 2>&1
				;;
			/proc/*/*)
				;;
			/proc/$$)
				;;
			/proc/*)
				p="${2%\\040(deleted)}"
				case "$1" in
					proc|systemd-?)
						pid="${p#/proc/}"
						[ -f "$proc_path/$pid/stat" ] || umount "$p" > /dev/null 2>&1
						;;
				esac
				;;
		esac
	done < /proc/1/mounts

	sleep 2 & wait $!
done
