#!/bin/bash
# mkdir-redir  -- redirected mkdir
# Copyright (c) 2009 Institute for Defense Analyses
# 
# "MIT" license
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# 

IFS=`printf '\n\t'`

progname="mkdir-redir"
err="${progname}: error: "

if `getopt -T >/dev/null 2>&1` ; [ $? -ne 4 ] ; then
  echo "$err Need an enhanced getopt(1) that can handle quoted text." >&2
  exit 1
fi

declare -a newargs
declare -a files
declare -i minus1=-1

TEMP=`getopt -o "m:pvZ:" \
      --long mode: --long parents --long verbose \
      --long context: \
      --long help --long version \
      -n "$progname"  -- "$@"`

# Do this to handle whitespace; see getopt(1).
eval set -- "$TEMP"

no_target_directory=""
target_directory=""

while true ; do
  case "$1" in
    -p|--parents|-v|--verbose|--help|--version)
      newargs[${#newargs[*]}]="$1"
      shift ;;
    -m|--mode|-Z|--context)
      # Pass through the option's required argument.
      newargs[${#newargs[*]}]="$1=$2"
      shift ; shift ;;

    -T|--no-target-directory) # FIXME: Should we do anything about this?
      no_target_directory=true
      newargs[${#newargs[*]}]="$1"
      shift ;;

    -t|--target-directory)
      if [ -n "$target_directory" ] ; then
        echo "$err Multiple target directoriess: '$target_directory' and '$2'" >&2
        exit 1
      fi
      target_directory="$2"
      shift ; shift ;;

    # FIXME:
    --) shift; break ;;
    -*) # Shouldn't normally get here (getopt should screen these),
        # but if we get here, handle it gracefully.
      echo "$progname: Warning - unrecognized option: $1" >&2
      newargs[${#newargs[*]}]="$1"
      shift ;;
    *) echo "$err Internal error with argument $1!" >&2 ; exit 1 ;;
  esac
done

for directory ; do
  redir_directory=`redir_name --write "$directory"`
  /bin/mkdir "${newargs[@]}" "$redir_directory" || exit
done

