#!/bin/sh
# 
# add.sh - add an explicit tag for a file
################################################################
# Copyright (C) 2001, 2002 Tom Lord
# 
# See the file "COPYING" for further information about
# the copyright and warranty status of this work.
# 

set -e 

################################################################
# special options
# 
# Some options are special:
# 
#       --version | -V
#       --help | -h
# 
if test $# -ne 0 ; then

  for opt in "$@" ; do
    case $opt in

      --version|-V) exec larch --version
                    ;;


      --help|-h)
                printf "add an explicit inventory tag\\n"
                printf "usage: add [options] FILE ... \\n"
                printf "\\n"
                printf " -V --version                  print version info\\n"
                printf " -h --help                     display help\\n"
                printf "\\n"
                printf "Create an explicit inventory tag for FILE (which may be a\\n"
		printf "regular file, symbolic link, or directory).\\n"
                printf "\\n"
                exit 0
                ;;

      *)
                ;;
    esac
  done
fi

################################################################
# Ordinary Options
# 
# 

while test $# -ne 0 ; do

  case "$1" in 

    --)			shift
    			break
			;;
			
    -*)                 printf "add: unrecognized option (%s)\\n" "$1" 1>&2
                        printf "try --help\\n" 1>&2
                        exit 1
                        ;;

    *)                  break
                        ;;
  esac

done



################################################################
# Ordinary Arguments
# 

if test $# -lt 1 ; then
  printf "usage: add [options] file ...\\n" 1>&2
  printf "try --help\\n" 1>&2
  exit 1
fi


################################################################
# Process Arguments
# 

seq=0

here="`pwd`"

for file in "$@" ; do

  file="$1"
  shift

  cd "$here"

  ################################################################
  # Sanity Check and Process Defaults
  # 

  if test ! -h "$file" -a -d "$file" ; then
    file_dir="$file"
    id_file="=id"
  else
    file_dir="`dirname \"$file\"`"
    file_basename="`basename \"$file\"`"
    id_file="$file_basename.id"
  fi

  cd "$file_dir"
  file_dir="`pwd`"
  wdroot="`larch tree-root`"

  ################################################################
  # Record
  # 

  cd "$file_dir"
  
  mkdir -p .arch-ids

  if test -e ".arch-ids/$id_file" ; then
    printf "add: already added\\n" 1>&2
    printf "\\n" 1>&2
    exit 1
  fi

  printf "%s %s %s\\n" `larch my-id --uid` "`date`" "$$.$seq" > ".arch-ids/$id_file"
  seq="$(($seq + 1))"

done
