#   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 3 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 <http://www.gnu.org/licenses/>.
#
# test the behavior of `execfail' not exiting an interactive shell
# added tests for changes in 10/2021 for preserving the traps across a failed
# exec

: ${THIS_SH:=./bash}
: ${TMPDIR:=/var/tmp}
TDIR=$TMPDIR/execdir-$$

mkdir $TDIR || exit 1
cp $THIS_SH $TDIR || exit 1
cd $TDIR || exit 1

shopt -s execfail

trap 'echo EXIT' EXIT 
trap 'echo USR1' USR1
trap '' TERM
trap

kill -s USR1 $$		# should run the trap

# ENOENT -- No such file or directory
# full pathname
rm -f /tmp/bash-notthere
exec /tmp/bash-notthere
# make sure we're still around
echo $0: ENOENT: after failed exec: $?
# relative pathname
rm -f bash-notthere
exec bash-notthere 

# EACCES - permission denied
rm -f x.sh x.output
echo 'echo bar' > x.sh
exec ./x.sh 2>x.output
string=$(< x.output)
# check for right error message and that we survived the failed exec
case $string in
*denied)	;;
*)	echo "$0: EACCES: error message mismatch: $string" ;;
esac
rm -f x.sh x.output

# E2BIG - Argument list too long
unset BASH_ENV
rm -f x.sh x.output
cat << \EOF > x.sh
argmax=$(getconf ARG_MAX 2>/dev/null)
if (( argmax <= 0 )); then
        argmax=1048576
fi
v=$(echo {1..250000})
while (( ${#v} < $argmax )); do
        v+=$(echo {250001..350000})
done
export v
exec ${THIS_SH} </dev/null
EOF
chmod 755 ./x.sh
${THIS_SH} ./x.sh 2>x.output
string=$(< x.output)
# check for right error message
case $string in
*list\ too\ long)	;;
*)	echo "$0: E2BIG: error message mismatch: $string" ;;
esac
rm -f x.sh x.output

# EISDIR - is a directory
rm -f x.sh x.output
mkdir xdir-$$
exec ./xdir-$$ 2>x.output
rmdir ./xdir-$$
string=$(< x.output)
# check for right error message and that we survived the failed exec
case $string in
*[Ii]s\ a\ directory)	;;
*)	echo "$0: EISDIR: error message mismatch: $string" ;;
esac
rm -f x.sh x.output

trap
kill -s USR1 $$		# should run the trap
kill -s TERM $$		# should still be ignored

cd $OLDPWD
rm -rf $TDIR

# this should run the exit trap
exit 0
