#!/bin/brash

alias ll='ls -l'

alias  which='type '


PATH=".;$PATH"

alias cls='cmd /c cls'
alias dir='.ls -l'
alias move='cmd /C move'
alias mkdir='cmd /C mkdir'
alias rename='cmd /C rename'
alias ren='cmd /C rename'
alias attrib=.attrib


del()
(
    for f in "$@"
    do
	   f1="${f//\//\\}"        # convert forward slash to backslash
	   file="${f1//\\\\/\\}"   # convert multiple backslash into single backslash
	   cmd /c del "$file"
    done
)




addPath()
{
   #
   #   add directory to the command search path.
   #

   if [ $# != 1 ]
   then
       echo $0 Error:  expected exactly one directory name on the command line
       return
   fi

   if [ "$1" = "-h" -o "$1" = "--help" ]
   then
       echo ""
       echo ""
       echo "addPath:  a shell function"
       echo ""
       echo "Abstract"
       echo "    Add a directory to the PATH variable"
       echo ""
       echo "Usage"
       echo "    addPath [-h | --help] directoryPathname"
       echo ""
       echo "Description"
       echo ""
       echo "    Appends the specified directory pathname onto the end of"
       echo "    the PATH variable in a manner appropriate to the OS.  On"
       echo "    Windows, this means using the ';' character as a separator."
       echo ""
      return
   fi


   fixedPath="`echo "$1" | .regex  -p '/'  -r '\\'`"

   PATH="$PATH${BRASH_PATH_SEPARATOR}$fixedPath"

   hash -r


}

listPath()
{
   #
   #   list the directories in the command search path
   #



   if [ "$1" = "-h" -o "$1" = "--help" ]
   then
       echo ""
       echo ""
       echo "listPath:  a shell function"
       echo ""
       echo "Abstract"
       echo '    List the names of the directories in the $PATH variable'
       echo ""
       echo "Usage"
       echo "    listPath [-h | --help]"
       echo ""
       echo "Description"
       echo ""
       echo "    Lists the names names of the directories comprising the"
       echo "    command search path.   Each name appears on a separate"
       echo "    line in the output."
       echo ""
      return
   fi

   if [ $# != 0 ]
   then
       echo "$0 error:  no parameters are allowed" 1>&2
       return
   fi


   echo "${PATH//${BRASH_PATH_SEPARATOR}/\n}"
}



if [ "$BRASH_OS" = "MSWindows" ]
then

    function sort
    {
       #
       #  define a sort command that invokes the windows sort command but which forces the
       #  use of a filter program which converts utf8 data (and more importantly, utf16
       #  data) into standard ascii characters before peforming the sort.
       #
       #  This is important because the microsoft sort command occasionally hangs which 
       #  sort the names of files in a directory where some of the files have UTF16
       #  encoded names.  Basically, there crap is broken and this is an attempt to
       #  work around the problem.
       #
    
       reverse=""

       if [ "$1" = "-r" ]
       then
	  reverse="/R"
	  shift
       fi

    
       if [ "$#" = 0 ]
       then
	   utf8dec
       else
	   for f in "$@"
	   do
	       if [ -r "$f" ]
	       then
		   utf8dec <"$f"
	       else
		   echo Unknown File:  $f 1>&2
	       fi
	   done
       fi  |
       if [ "$reverse" = "" ]
       then
	   C:/Windows/System32/sort.exe 
       else
	   C:/Windows/System32/sort.exe $reverse
       fi
    }

fi

#
#   The following code creates functions for all mounted file systems
#
#   These functions are named:   p:, q:, s:, etc
#

c:() { pushd c:/ ; }

net use | 
 .regex -m '[A-Z]:' |
while read status local rest
do
   # fix up missing status

    case "$status" in
       *:)   
	   # status was empty
	   # slide the other fields over 1
	   # and put unknown in the status


	   rest="$local $rest"
	   local="$status"
	   status="unknown"
	   ;;
    esac

    case "$status" in
       OK)
	   echo "${local,,}() { echo pushd $local ; pushd $local/; }"
	   ;;
    esac

done | read -f cmd

eval "$cmd"

unset cmd


copy()
{
    
    
    if [ "$1" = "-h" -o \
	 "$1" = "--help" ]
    then
	echo "copy:  copy one or more files to a destination directory or file"
	echo ""
	echo "Usage:"
	echo ""
	echo "   copy source [...]   target"
	echo "Description"
	echo ""
	echo "   Copy the source files to the target.  If the target is a directory"
	echo "   then the source files are copyied into the directory keeping the same name."
	exit 1
    fi
    
    if (( $# < 2 ))
    then
       echo "Error:  expected source file name(s) and destination directory or file" 1>&2
       return 1
    fi
    
    #
    #  confirm the existence of all files but the target
    #
    
    bad=false
    
    let count=1
    for f in "$@" 
    do
    
	  if (( $count != $# ))
	  then
	      if [ ! -r "$f" ]
	      then
		  echo "Error:  cannot find $f" 1>&2
		  bad=true
	      fi
	  fi
    
	  let count++
    done
    
    
    if [ "$bad" != "false" ]
    then
       echo $0 error -- cannot continue 1>&2
       return 1
    fi
    
    #
    #  If multiple files are specified, confirm that the target is a directory
    #
    
    : "$@"   # set the $_ variable to be the last command line option
    
    target=$_
    
    if (( $# > 2 ))
    then
    
	if [ ! -d "$target" ]
	then
	    echo $0:  Error, multiple source files but $target is not a directory 1>&2
	    return 1
	fi
    
    fi
    
    #
    #   perform the actual copy
    #
    
    echo Copying
    let count=1
    for f in "$@"
    do
	if (( $# != count ))
	then
	    echo "    $f"
	    if ! cmd /C copy /Y "${f//\//\\}" "${target//\//\\}" 1>nul
	    then
		echo "Error copying $f to $target"
	    fi
	fi
    
    
	let count++
    done

    return $?
    

}

function cp
{
    
    
    if [ "$1" = "-h" -o \
	 "$1" = "--help" ]
    then
	echo "cp:  copy one or more files/directories to a destination directory or file"
	echo ""
	echo "Usage:"
	echo ""
	echo "   cp [-r | -h | --help] source [...]   target"
	echo "Description"
	echo ""
	echo "   Copy the source files/directories to the target.  If the target is a directory"
	echo "   then the source files are copyied into the directory keeping the same name."
	exit 1
    fi

    #
    #   we are going to use either the windows copy command or the windows xcopy command to
    #   perform the actual copies
    #
    #   The xcopy command is used on directories and we will pass /s /e and /I to it.
    #
    #

    recursiveOptions=""              # flag meaning that we are going recursive on directories

    if [ "$1" = "-r" ]
    then
	recursiveOptions="/s /e /I /Y"
	shift
    fi

    if (( $# < 2 ))
    then
       echo "Error:  expected source file name(s) and destination directory or file" 1>&2
       return 1
    fi
    
    #
    #  confirm the existence of all files but the target
    #
    
    bad=false
    
    let count=1
    for f in "$@" 
    do
    
	  if (( $count != $# ))
	  then
	      if [ ! -r "$f" ]
	      then
		  echo "Error:  cannot find $f" 1>&2
		  bad=true
	      fi
	  fi
    
	  let count++
    done
    
    
    if [ "$bad" != "false" ]
    then
       echo $0 error -- cannot continue 1>&2
       return 1
    fi
    
    #
    #  If multiple files are specified, confirm that the target is a directory
    #
    
    : "$@"   # set the $_ variable to be the last command line option
    
    target=$_
    
    if (( $# > 2 ))
    then
    
	if [ ! -d "$target" ]
	then
	    echo $0:  Error, multiple source files but $target is not a directory 1>&2
	    return 1
	fi
    
    fi
    
    #
    #   perform the actual copy
    #
    
    echo Copying
    let count=1
    for f in "$@"
    do
	if (( $# != count ))
	then

	    if [ "$recursiveOptions" = "" -a -d "$f" ]
	    then
		echo "Error, directory $f cannot be copied without -r"
		return 1
	    else
		echo "    $f"

		# xcopy is buggy.  You cannot copy a file from the current directory to a child of the current directory,
		# but you can make it work if you use the fully qualified pathnames.  One can only hope that there is
		# is justice in the afterlife.

		# now see where the source file is


		sourceIsLocal=true
		sourcePrefix=""

		case "$f" in
		   /*)
		       sourceIsLocal=false
		       ;;
		   \\*)
		       sourceIsLocal=false
		       ;;
		   [a-z]:*)
		       sourceIsLocal=false
		       ;;
		   *)
		       sourcePrefix="$PWD\\"
		       ;;
		esac



		targetIsLocal=true
		targetPrefix=""

		case "$target" in
		   /*)
		       targetIsLocal=false
		       ;;
		   \\*)
		       targetIsLocal=false
		       ;;
		   [a-z]:*)
		       targetIsLocal=false
		       ;;
		   *)
		       targetPrefix="$PWD\\"
		       ;;
		esac

		fixedTarget="${target//\//\\}"

		if [ -d "$fixedTarget" ]
		then
		    fixedTarget="$fixedTarget\\$(basename "$f")"
		fi

		if [ ! -d "$f" ]
		then
		     #
		     #  copy files using the standard windows cmd.exe tool
		     #
		     if ! cmd /C copy /Y "${f//\//\\}" "${target//\//\\}" 1>nul
		     then
			 echo "Error copying $f to $target"
		     fi
		else
		     #
		     #  copy a directory using xcopy
		     #
		     (
			 if ! xcopy $recursiveOptions "$sourcePrefix${f//\//\\}" "$targetPrefix$fixedTarget" 1>nul
			 then
			     echo "Error copying $f to $target"
			 fi
		     
		     )
		fi

	    
	    fi

	fi
    
    
	let count++
    done

    return $?
    

}

rmdir()
(
    if [ "$1" = "-h" -o "$1" = "--help" -o "$1" = "/?" ]
    then
	echo ""
	echo "Remove Directory"
	echo ""
	echo "  rmdir [options] dir ..."
	echo ""
	echo "Options:"
	echo ""
	echo "   -r -- recursive"
	echo "   /s -- recursive"
	return 0;
    fi

    recursiveOptions=""

    while [ "$1" =~ /s   -o  "$1" =~ -r ]
    do
	  recursiveOptions="$recursiveOptions /s /q"

	  shift
    done
				    
    cmd /c rmdir $recursiveOptions "${@//\//\\}"
)


rm()
(
    if [ "$1" = "-h" -o "$1" = "--help"  -o "$1" = "/?" ]
    then

	cat <<*eof

rm:  remove files and directories

Usage:  rm [ -[ r | f ] ] path ...

Description:

    Delete files or directories -- possibly recursively.  

    If you delete directories recursively, read only files within them
    will be deleted.

    When deleting individual files, the -f option must be specified for
    read-only files to be deleted.

    Options:

      r  recursively delete directories and files
      f  force the deletion of read-only files

*eof

       return 1
    fi


    recursive=
    force=

    while [ "$1" =~ "^-" ]
    do
	  #
	  #  check for -r -f but error out if other options
	  #  are specified
	  #

	  if [ "$1" =~ "r" ]
	  then
	      recursive="/S /Q"
	  fi

	  if [ "$1" =~ "f" ]
	  then
	     force=/F 
	  fi

	  #
	  #  now check for other options that should trigger
	  #  error message
	  #

	  echo -- "$1" | .regex -p "[-rf]" -r "" | read leftOverOptions

	  if [ "$leftOverOptions" != "" ]
	  then
	      echo $0 error, Invalid options $leftOverOptions 1>&2
	      return 1
	  fi


	  shift  # eat the -r or -f or -rf
    done

    echo Deleting 1>&2

    for f in "$@" 
    do
	   echo "    $f"

	   if [ -d "$f" ]
	   then
	       if [ "$recursive" = "" ]
	       then
		   echo ignoring directory $f 1>&2
	       else
		   #rundequoted.bat cmd 4 /c rmdir $recursive "$f"
		   cmd /c rmdir $recursive "${f//\//\\}"
	       fi
	   else
	       #rundequoted.bat cmd  3 /c del $force "$f"
	       cmd  /c del $force "${f//\//\\}"
	   fi
    done


    return $?

)

unix2dos()
{
    if [ $# != 0 ]
    then
	.regex -p ".*" -r "\\0\r" "$@"
    else
	.regex -p ".*" -r "\\0\r" 
    fi
}

