#!/bin/ksh

DIRECTORY=$1
USER_ID=$2
GROUP_ID=$3
MOD=$4
DEBUG_LOG_DIRECTORY=$5
DEBUG_LOG_FILE=$6
LOG_DEBUG=$7

FATAL_ERROR=1000

ORIGINAL_IFS=$IFS
IFS="/"


#
# print debug string to appropriate location
#
# $1=debug string to be printed
#
print_debug()
{
  ./debug_handler.ksh "$0" "" "$1" "$DEBUG_LOG_DIRECTORY" "$DEBUG_LOG_FILE" "$LOG_DEBUG"
}



count=0
directory=""

for next_directory in ${DIRECTORY}
do
    if test "$next_directory"
    then
        directory=$directory/$next_directory

        if ! test -e "$directory"
        then
            ##  The directory does not exist.  Let's try an create it.
            if ! mkdir "$directory"
            then
                print_debug "Could not create directory: $directory"
                ERROR=`./error_handler.ksh $FATAL_ERROR`
                printf "ERROR: $ERROR\n"
                exit 1
            fi

            ##  Set ownership and permissions on the directory
            if test "$USER_ID" && test "$GROUP_ID"
            then
                if ! chown $USER_ID:$GROUP_ID "$directory"
                then
                    print_debug "Warning: Could not change ownership to $USER_ID:$GROUP_ID"
                    print_debug "         on the following directory:"
                    print_debug "         $directory"
                    print_debug
                fi
            fi

            if test "$MOD"
            then
                if ! chmod $MOD "$directory"
                then
                    print_debug "Warning: Could not change permissions to $MOD"
                    print_debug "         on the following directory:"
                    print_debug "         $directory"
                    print_debug
                fi
            fi

        elif ! test -d "$directory"
        then
            ##  The name exists, but it is not a directory.
            print_debug "$directory in $DIRECTORY is not a directory"
            ERROR=`./error_handler.ksh $FATAL_ERROR`
            printf "ERROR: $ERROR\n"
            exit 1
        fi
    fi
done

IFS=$ORIGINAL_IFS


exit 0
