#!/bin/bash
# chmod-redir  -- redirected chmod
# Copyright (c) 2009 David A. Wheeler and 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="chmod-redir"
err="${progname}: error: "

# We don't use getopt(1), because chmod has options that have "=" in
# random places.

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

# Process options (if any)
while [ $# -gt 0 ] ; do
  case "$1" in
    --reference|--reference=*)
      # Documentation requires that this is the LAST option.
      break ;;
    --) shift; break ;;
    # The single-option-letter commands could combine, e.g., "-cfr",
    # but since none have options, we don't need to do complicated
    # processing of them by splitting them up, etc.  Just pass them on!
    #   -c|--changes|--no-preserve-root|--preserve-root|-f|--silent|--quiet|
    #   -v|--verbose|-R|--recursive|--help|--version)
    -*)
      newargs[${#newargs[*]}]="$1"
      shift ;;
    *)  break ;;  # Not an option - stop processing options.
  esac
done

# Process mode
if [ $# -eq 0 ] ; then
  echo "No mode provided."
  exit 1
fi
case "$1" in
  # For "--reference", prefer the new file if it exists, else use old file.
  --reference=*)
    oldfile="${1#'--reference='}"
    newfile=`redir_name --read "$oldfile"`
    newargs[${#newargs[*]}]="--reference=${newfile}"
    shift ;;
  --reference)
    newargs[${#newargs[*]}]="$1"
    shift
    newfile=`redir_name --read "$1"`
    newargs[${#newargs[*]}]="$newfile"
    shift
    break ;;
  *) # Normal mode statement - just pass it through.
    newargs[${#newargs[*]}]="$1"
    shift ;;
esac

# Process filenames.  They are supposed to already exist.
if [ $# -eq 0 ] ; then
  echo "No filenames provided."
  exit 1
fi
for file
do
  newname=`redir_name --write "$file"`
  newargs[${#newargs[*]}]="$newname"
done

# Execute new resulting command.
exec /bin/chmod "${newargs[@]}" || exit

