#!/bin/sh
# dmc - dynamic mail client
# See LICENSE file for copyright and license details.
# TODO: rewrite in C

VERSION="0.1"

[ -z "${DMCTAG_ROOT}" ] && \
	DMCTAG_ROOT="${HOME}/.dmctag"
if [ ! -d "${DMCTAG_ROOT}" ]; then
	mkdir -p "${DMCTAG_ROOT}"
	if [ ! $? = 0 ]; then
		echo "Cannot create \${DMCTAG_ROOT}"
		exit 1
	fi
fi
cd ${DMCTAG_ROOT}

set_file () {
	FILE=$1
	if [ ! "`echo ${FILE} | cut -c 1`" = / ]; then
		# autocomplete relative paths
		FILE="${OLDPWD}/${FILE}"
	fi
	if [ ! -e "${FILE}" ]; then
		echo "Cannot find ${FILE}"
		exit 1
	fi
	export FILE
}

# untag this file . this is highly suboptimal. in C will be much faster
# XXX: Only used with $FILE.. set_file is required
untag () {
	for TAG in `$0 -l` ; do
		grep -v $1 $TAG > $TAG.tmp
		mv $TAG.tmp $TAG
	done
}

case "$1" in
"-f")
	cat * 2> /dev/null | sort | uniq
	;;
"-m")
	# move cached files in from to
	for a in `$0 -l` ; do
		sed -e "s,^$1,$2," $a > $a.tmp
		mv $a.tmp $a
	done
	;;
"-c")
	# check/cleanup for missing files
	if [ -n "$2" ] ; then
		set_file "$2"
		if [ -z "`cat * 2> /dev/null | grep $FILE`" ]; then
			rm -f "${FILE}"
		fi
	else
		for a in `$0 -f` ; do
			if [ ! -e $a ]; then
				echo Untag missing file $a
				untag ${FILE}
			fi
		done
	fi
	;;
"-l")
	if [ -z "$2" ]; then
		ls | cat
	else
		# XXX buggy: does not supports filenames with spaces
		tag0=$2
		shift ; shift
		for a in `cat ${DMCTAG_ROOT}/${tag0}`; do
			for b in $* ; do
				a="`grep "$a" ${DMCTAG_ROOT}/$b`"
				[ -z "$a" ] && break
			done
			[ -n "$a" ] && echo $a
		done
	fi
	;;
"-u")
	set_file "$2"
	untag ${FILE}
	;;
"-v")
	echo "dmc-tag v${VERSION}"
	;;
"")
	echo "Usage: dmc-tag [-uhv] [-l [tag ..]] [-c [file ..]] [-m dir dir] [file ..]"
	;;
"-h")
	$0
	echo " dmc-tag file            # get tags of file"
	echo " dmc-tag file tag1 tag2  # set tags of file"
	echo " dmc-tag -u file         # untag file"
	echo " dmc-tag -m dir1 dir2    # move files from dir1 to dir2 in tags"
	echo " dmc-tag -f              # list all tagged files"
	echo " dmc-tag -l              # list tags"
	echo " dmc-tag -l tag1 tag2    # list files matching tag1+tag2"
	echo " dmc-tag -c              # check tag consistency. untag all nonexistent files"
	echo " dmc-tag -c file         # remove file if not tagged"
	echo " dmc-tag -v              # show version"
	echo " dmc-tag -h              # show this help"
	;;
*)
	if [ -z "$2" ]; then
		# get tags of given file
		set_file "$1"
		grep "$1" * | cut -d : -f 1
	else
		# set tags for a file
		set_file "$1"
		untag "${FILE}"
		while [ -n "$2" ] ; do
			[ -z "`grep $FILE ${DMCTAG_ROOT}/$2`" ] && \
				echo "$FILE" >> ${DMCTAG_ROOT}/$2
			shift
		done
	fi
	;;
esac
