#!/bin/sh
##################################
#
# Test creation of temporary file.
#
##################################

set -e

if test -z "${MH_OBJ_DIR}"; then
    srcdir=`dirname "$0"`/../..
    MH_OBJ_DIR=`cd "$srcdir" && pwd`; export MH_OBJ_DIR
fi

. "$MH_OBJ_DIR/test/common.sh"

setup_test

expected="$MH_TEST_DIR"/$$.expected
actual="$MH_TEST_DIR"/$$.actual

mkstemp="${MH_LIBEXEC_DIR}/mkstemp"

check_exit '-eq 255' $mkstemp -

$mkstemp -help | grep suffix >/dev/null  &&  has_mkstemps=1  ||  has_mkstemps=0

cd "$MHTMPDIR"


# check -help
if [ $has_mkstemps -eq 1 ]; then
    cat >$expected <<-'EOF'
	Usage: mkstemp [switches]
	  switches are:
	  -directory
	  -prefix
	  -suffix
	  -version
	  -help
	EOF
else
    cat >$expected <<-'EOF'
	Usage: mkstemp [switches]
	  switches are:
	  -directory
	  -prefix
	  -version
	  -help
	EOF
fi

#### Skip nmh intro text.
run_prog $mkstemp -h 2>&1 | sed '/^$/,$d' >"$actual"
check "$expected" "$actual"


# check -version
# Verified same behavior as compiled mhmail.
case `$mkstemp -v` in
    mkstemp\ --*) ;;
    *           ) printf '%s: mkstemp -v generated unexpected output\n' "$0" >&2
                  failed=`expr ${failed:-0} + 1`;;
esac


# check with no switches
tmpfile=`$mkstemp`
if [ -f "$tmpfile" ]; then
    rm "$tmpfile"
else
    failed=1
fi


# check -directory
tmpfile=`$mkstemp -directory "$MHTMPDIR"`
[ -f "$tmpfile" ]  &&  rm "$tmpfile"  ||  failed=`expr ${failed:-0} + 1`
# Rely on exit status of grep to detect failure and terminate due to set -e:
check_tmpfile=`echo $tmpfile | grep "^$MHTMPDIR/......$" >/dev/null`
run_test 'eval echo $check_tmpfile' ''


# check -prefix
tmpfile=`$mkstemp -prefix mkstemptest`
[ -f "$tmpfile" ]  &&  rm "$tmpfile"  ||  failed=`expr ${failed:-0} + 1`
# Rely on exit status of grep to detect failure and terminate due to set -e:
check_tmpfile=`echo $tmpfile | grep '^mkstemptest......$' >/dev/null`
run_test 'eval echo $check_tmpfile' ''


if [ $has_mkstemps -eq 1 ]; then
    # check -suffix
    tmpfile=`$mkstemp -suffix .txt`
    [ -f "$tmpfile" ]  &&  rm "$tmpfile"  ||  failed=`expr ${failed:-0} + 1`
    # Rely on exit status of grep to detect failure and terminate due to set -e:
    check_tmpfile=`echo $tmpfile | grep '^......\.txt$' >/dev/null`
    run_test 'eval echo $check_tmpfile' ''
fi


exit $failed
