#! /bin/ksh

set -x

if [[ "$#" -lt 1 ]] ; then
cat<<EOF 1>&2
ERROR.  Format: $0 /path/to/new/dir [ /another/path [...] ]

This script is a replacement for "mkdir -p" and works around an AIX
bug.  If multiple processes try to run mkdir -p on the same directory
at the same time, then the mkdir -p can fail if one process tries to
make an anscestor directory that another process just made.  The
second process receives EEXIST and aborts (see mkdir(2) and errno.h).
This error happens remarkably often if multiple scripts are started
simultaniously and all try to make a directory near the beginning of
the script.

This workaround will try to run mkdir -p multiple times, and sleep
random amounts of time (1-5 seconds) between failures.  (Sleeping a
constant amount of time does not reliably resolve the problem.)
EOF
exit 2
fi

function safe_mkdirp_impl {
set -x
    Dir="$1"
    Try=0
    MaxTries=5
    while (( Try<MaxTries )) ; do
        mkdir -p "$Dir"
        if [[ ! -d "$Dir" ]] ;  then
            if [[ "$Try" -lt "$MaxTries" ]] ; then
                echo "$Dir: creation failed.  Try again..." 1>&2
                sleep $(( ( RANDOM % 5 ) +1 ))
            else
                echo "Unable to create directory \"$Dir\"" 1>&2
                return 1
            fi
        else
            return 0
        fi
        let 'Try=Try+1'
        sync # update filesystem metadata
    done
    return 1
}

finalret=0
for xDir in "$@" ; do
    safe_mkdirp_impl "$xDir"
    ret="$?"
    if [[ "$ret" -gt "$finalret" ]] ; then
        finalret="$ret"
    fi
done

exit $finalret
