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

# Doesn't use getopt(1), so we can more robustly handle unknown options.
# (We're better off passing unknown options on to the "real" program.)
# The downside is that this doesn't handle combining option letters
# (e.g., -dt) with parameters that look like redirectable filenames,
# though that's a pretty unlikely circumstance.

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

# Process options (if any)
while [ $# -gt 0 ] ; do
  case "$1" in
    -d|--date|-t|--time)   # Additional mandatory parameter
      newargs[${#newargs[*]}]="$1"
      shift
      newargs[${#newargs[*]}]="$1"
      shift ;;
    --date=*|--time=*)  # Parameter built in.
      newargs[${#newargs[*]}]="$1"
      shift ;;
    --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 ;;
    --) shift; break ;;
    -*)
      newargs[${#newargs[*]}]="$1"
      shift ;;
    *)  break ;;  # Not an option - stop processing options.
  esac
done

# Process filenames, we need at least one.
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.
/bin/touch "${newargs[@]}"

