#!/bin/sh -

todo="$HOME/tmp"
work="$HOME/work"
when='tomorrow'

# todo - conveniently move files between todo and work directories
# Steve Kinzler, steve@kinzler.com, Jan 11/Jun 14/Mar 15
# https://kinzler.com/me/home.html#unix

patt='todo_?*_2???????'; dotpatt=".$patt"; dot=.
case "$1" in
-a)	dotpatt=; shift;;
esac

and=
case "$1" in
-d)	and=' && $1 <= '"`date +%Y%m%d`";;
-D)	and=' && $1 >  '"`date +%Y%m%d`";;
esac

dodo=
case "$1" in
-.)	dot=;  shift;;

-o)	dodo=t; shift;;

-[dDA])	exec perl -e 'for (@ARGV) { print "$_\n" if /_(2[^?]{7})$/'"$and }" \
		"$todo"/$dotpatt "$todo"/$patt;;

-x)	exec perl -ne 'print unless /\btodo_[^\/]+_2.......($| -> )/';;

-h)	cat <<EOF 1>&2
usage: $0 [ -a ] [ [ -. | -o ] [ +when ] file ... | -d | -D | -A | -x ]
	-a	exclude .todo files from listings
	-.	don't use .todo filenames when moving files into the todo dir
	-o	move files out of todo directory (default into)
		default all due files if none listed
	+when	absolute or relative date for due date (default "$when")
	-d	list any due todo files (default if no files listed)
	-D	list any undue todo files
	-A	list all todo files
	-x	act as a filter for lines not ending in a todo file
+when date formats are as with \`date -d when\`.
EOF
	exit 1;;
esac

case "$#" in
0)	case "$dodo" in
	?*)	case "`$0 -d`" in
		'')	exit;;
		esac
		exec $0 -o `$0 -d`;;
	'')	exec $0 -d;;
	esac;;
esac

case "$1" in
+*)	when=`echo "$1" | sed s/+//`; shift;;
esac

for file
do
	base=`basename "$file"`
	case "$dodo" in
	?*)	dest="$work/`echo "$base" |
			     perl -pe 's/^\.?todo_//; s/_2.......$//'`"
		echo "mv -i $file $dest"; mv -i "$file" "$dest";;

	*)	dest="$todo/${dot}todo_${base}_`date +%Y%m%d -d "$when"`"
		echo "mv -i $file $dest"; mv -i "$file" "$dest";;
	esac
done
