#!/bin/bash
#
# __copy1__
# __copy2__
#
# original author: Lorenzo Canovi (lorenzo@kubiclabs.com)
#
CMD=$(basename $0)
CMDVER="2.0"
CMDSTR="$CMD v$CMDVER (2023-07-26)"

usage()
{
	echo "
== $CMDSTR == checks for chroot envinronment == 

usage: $CMD [options]

options:
  -v|--verbose
  -vv			be more verbose

returns:
  0	(true) we are in a chroot jail
  1	(false) we are not
" >&2
	exit 127
}


be_verbose()
{
	$VERBOSE && { echo -e "\n$CMD: $1\n"; return 0; }
	$more_verbose || return 0

	echo "
  $CMD: $1

  init root:   $init_root
  local root:  $local_root
"
	return 0
}



# (MAIN)

VERBOSE=false
more_verbose=false

case ${1:-} in
  -v|--verbose) VERBOSE=true; shift ;;
  -vv|--vv)	more_verbose=true; shift ;;
esac

[ $# != 0 ] && usage

# a quick test can be done on root file system against init process
# (proc 1) root file system, if they are not the same, we are in
# a chroot jail
#
#  test $(stat -c '%d:%i' /) != $(stat -c '%d:%i' /proc/1/root/.)
#
# sadly, this require to have root access, since /proc/1/root/.  is not
# world readable


# a little more tricky, but user accessibile, is to use /proc/1/mountinfo,
# that is world readable (mountinfo is readable for all processes)
#
# in the mountinfo table we have an entry marked ' / / ' for the root
# filesystem (the second slash, the 5th field, is the mountpoint of the
# entry, that is, of course, '/' for the root)
#
# we check the init (proc 1) entry against the current shell entry,
# if the two doesn't matches, we are in a chroot jail
#
init_root=$(fgrep ' / / ' /proc/1/mountinfo)
local_root=$(grep ' / / ' /proc/$$/mountinfo)
state=

[ "X$init_root" = "X$local_root" ] && {
	be_verbose 'false'
	exit 1
}

be_verbose 'true'
exit 0
