#!/usr/bin/env bash
#
# Add files to the GIT repository.
# Copyright (c) Petr Baudis, 2005
#
# Takes a list of file names at the command line, and schedules them
# for addition to the GIT repository at the next commit.
#
# The command will fail if one of the given files does not exist.
#
# Note that directories never have to be added to the repository, and are
# not tracked on their own. That means, you cannot currently add an empty
# directory to 'Cogito'. The reason for this is that 'Cogito' manages
# content and empty directories have no content. Directories are added
# automatically when adding files inside them, or you can add all files in
# a directory using cg-add -r.
#
# OPTIONS
# -------
# -N::
#	Only update the cache: do not copy the data into the object database.
#	This is for special purposes when you might not actually _have_ any
#	object database. This option is normally not interesting.
# -r::
#	If you pass cg-add this flag and any directory names, it will try
#	to add files in those directories recursively (with regard to your
#	ignore rules - see cg-status documentation for more detailed
#	description of those). See also above for more notes about cg-add
#	vs. directories.

USAGE="cg-add [-N] [-r] FILE..."

. ${COGITO_LIB}cg-Xlib || exit 1

infoonly=
recursive=
while optparse; do
	if optparse -N; then
		infoonly=--info-only
	elif optparse -r; then
		recursive=1
	else
		optfail
	fi
done

[ "$ARGS" ] || usage

TMPFILE=$(mktemp -t gitadd.XXXXXX) || exit 1
error=
for file in "${ARGS[@]}"; do
	absfile="$_git_relpath$file"
	if [ -d "$absfile" ]; then
		if [ "$recursive" ]; then
			list_untracked_files exclude | tr '\0' '\n' |
				while IFS=$'' read path; do
					[ x"${path#$absfile}" != x"$path" ] &&
						echo "$file${path#$absfile}" >>$TMPFILE
				done
		else
			echo "$file is a directory (use cg-add -r?)" >&2
			error=1
		fi
	elif [ ! -f "$absfile" ]; then
		echo "$file does not exist or is not a regular file" >&2
		error=1
	else
		echo "$file" >>$TMPFILE
	fi
done

cat $TMPFILE | sed 's/^/Adding file /'
cat $TMPFILE | sed "s|^|$_git_relpath|" | path_xargs git-update-index --add ${infoonly} -- || error=1

rm $TMPFILE

[ "$error" ] && die "warning: not all files could have been added"
exit 0
