#!/bin/bash

###############################################################################
# tasknote - associate note file with individual tasks in taskwarrior
# http://taskwarrior.org/projects/1/wiki/Tasknote
#
# Copyright 2011, Alan Bowen, bowen@tcnj.edu.
# All rights reserved.
#
# based on taskopen - file based notes with taskwarrior
#
# Copyright 2010, Johannes Schlatow.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the
#
#     Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor,
#     Boston, MA
#     02110-1301
#     USA
#
###############################################################################

EDITOR=sensible-editor
TASKBIN=task

# If you sync tasks FOLDER should be a location that syncs and is available to
# other computers, i.e. /users/dropbox/tasknotes
# FOLDER to store notes in, must already exist!
#FOLDER="/users/dropbox/taskwarrior/tasknotes/"
FOLDER="${HOME}/.task/notes/"

# Preferred extension for tasknotes
EXT=".txt"

# Message that gets annotated to the task to indicate that notes exist
NOTEMSG="Notes"

# Display usage if task number not supplied on cli
if [ $# != 1 ]; then
	echo "Usage: $0 <id>"
	exit 1
fi

# Find UUID from given task
uuid=$($TASKBIN rc._forcecolor=no rc.defaultwidth=300 $* | grep UUID | grep -o "[-a-f0-9]*\$")

# build full path & file name to store notes in
file="$FOLDER$uuid$EXT"

# determine if notes file already exists
fileexists=0
if [ -f $file ]; then
  fileexists=1
else
  head=$($TASKBIN ls | head -n 2 | tail -n 1)
  text=$($TASKBIN ls | grep ^$*)
  echo "# ${head}" > $file
  echo "# ${text}" >> $file
fi

#create/edit $file with editor
$SHELL -c "$EDITOR $file"

# if note was just created, add NOTEMSG as annotation to task
if [ $fileexists = 0 ]; then
  if [ -f $file ]; then
    $SHELL -c "$TASKBIN $* annotate $NOTEMSG"
 fi
fi

exit 0

