#!/bin/bash
# PURPOSE: Translate M$ DOS style-path into cygwin-style path [and cd into it]
# AUTHOR: Jakub Holy
# May 2, 2004
#
# Use aliases:
#       alias p2cygwin='/cygdrive/c/mydir/path2unix.sh' # translate the path
#       alias cdwin='. /cygdrive/c/mydir/path2unix.sh -cd' # change into the dir.

#Parameters: $1 = environmental variable RESULT123 (or ""), rest: a path or flags
translate_path()
{
        #Define local variables not to overwrite environment variables;
        local DRIVE RPATH OLD_RESULT123="$1"
        shift 1; # remove env. variable RESULT123 from the positional variables.
        #Test that a path or a flag other then -cd has been given
        if [ -z "$1" ]; then echo "Usage: `basename $0` [-cd] '<DOS PATH>'"; return 1; fi
        case "$1" in ( '-h' | '-help' | '--help' )
        echo "`basename $0` translates M\$ DOS style-path into cygwin-style path"
        echo "Usage: `basename $0` [-cd] <DOS PATH>"
        echo "Usage: `basename $0` -h || -help || --help"
        echo "The <DOS PATH> must be enclosed by \' and \' (it contains '\\')"
        echo '-cd changes into the directory; for this to work the script'
        echo '    must not be executed by interpreted == called as: $ . path2unix.sh ...'
        return 1;;      
        esac
        
        # Change drive to /cygdrive/<drive-lowercase>:
        DRIVE="`echo \"$1\" | tr '[A-Z]' '[a-z]' | cut -s -d':' -f1`";
        # Check that DRIVE == a letter, if not set it to an empty string
        # expr returns 0 if the string is matched (i.e. if it prints 1, $? is 0 and v.v.)
        if expr  "$DRIVE" : '[a-zA-Z]$' > /dev/null
        then DRIVE="$(echo "/cygdrive/${DRIVE}")"
        else DRIVE=""
        fi
        
        # Change slashes from \ to /:
        RPATH="$(echo "$1" | cut -d':' -f2- | tr '\\' '/' )"
        
        # Store the result into $0 positional variable          
        RESULT123="`echo \"${DRIVE}${RPATH}\"`"
        return 0;
} # /translate_path

# Print the result or go into the directory:
if [ "$1" == '-cd' ]
        then \
        echo 'For -cd to work the script must be called as: '
        echo "\$ . path2unix.sh -cd '<path>'"
        shift 1
        # Store the env. variable RESULT123 into $1, if it exists not to overwrite it;
        set -- "${RESULT123:-"RESULT123_is_unset"}" "$@";      
        if translate_path "$@"; then cd "$RESULT123"; fi
        else \
        # Store the env. variable RESULT123 into $1, if it exists not to overwrite it;
        set -- "${RESULT123:-"RESULT123_is_unset"}" "$@";
        if translate_path "$@"; then echo "$RESULT123"; fi
fi

# Restore the variable RESULT123 if it was set:
if [ "$1" != "RESULT123_is_unset" ]; then RESULT123="$1"; fi