
# md - This function makes a directory even if the parent dir doesn't exist
#      usage:  md [-c] <directory_to_create>

if [ "$1" = "-c" ]
then
	ArGs=$1
	shift
fi

# see if they typed anything at all
if [ "$1" = "" ]
then
	echo "Error: You must give a full pathname"
	exit 1
fi

# If its not a FULL pathname, exit 1
if [ `echo $1 | awk '{ printf "%s\n", substr($0, 1, 1) }'` != / ]
then
	echo "Error: $1 isn't a FULL pathname (doesn't start with /)"
	exit 1
fi

# if its an ordinary file, exit 1
if [ -f $1 ]
then
	echo "Error: $1 is an ordinary file"
	exit 1
fi

#if its an existing directory exit 0
if [ -d $1 ]
then
	if [ "$ArGs" = "-c" ]	# -c: check for priviledge only
	then
		touch $1/testcase 2> /dev/null
		if [ -f $1/testcase ]
		then
			rm -f $1/testcase	# priviledges OK
		else
			exit 2				# no priviledges
		fi
	fi
	exit 0
fi

MDDIR=`echo $0 | sed 's|/[^/]*.$||g'` # dirname
#if its parent doesn't exist, make it, if we can't, exit 1

pdir=`echo $1 | sed 's/\/[-_.:,[a-zA-Z0-9]*$//'` # find parent directory
if [ "$pdir" ]
then
	if [ ! -d $pdir ]
	then
		$0 $ArGs $pdir			# recursively call
		if [ "$?" = 2 ]			# bad permission?
		then
			exit 2				# no priviledges
		fi
		if [ "$ArGs" = "-c" ]	# -c: check for priviledge only
		then
			exit 0
		fi
		if [ -d $1 ]			#if its an existing directory exit 0
		then
			exit 0
		fi
	fi
fi

if [ "$ArGs" = "-c" ]	# -c: check for priviledge only
then
	mkdir $1 2> /dev/null
	if [ -d $1 ]
	then
		rmdir $1
		exit 0
	else
		exit 2				# no priviledges
	fi
fi

# if we got this far, we can try to make the directory
if mkdir $1
then
	chmod 777 $1
	echo $1 > ${MDDIR}/ttt.tmp
	touch ${MDDIR}/Dirlist
	cat ${MDDIR}/ttt.tmp ${MDDIR}/Dirlist > ${MDDIR}/ttt.jnk
	mv ${MDDIR}/ttt.jnk ${MDDIR}/Dirlist
	rm -f ${MDDIR}/ttt.tmp ${MDDIR}/ttt.jnk
	exit 0
else
	if [ -d $1 ]
	then
		exit 0
	fi
	echo "Error: unable to create the directory $1"
	exit 1
fi
