#!/usr/bin/sh
# snotes-1.0 by v4hn / 2009-2013
# See LICENSE file for copyright and license details.

info(){
    echo "$0: Info: $1" >&2
}

die(){
    echo "$0: Error: $1" >&2
    exit 1
}

newtemp(){
    local tmp
    tmp="`mktemp -t snotes.tmp.XXXXXX`"
    [ -e "$tmp" ] || die "Could not create temporary file"
    echo $tmp
}

type git >/dev/null 2>&1 || die "git not in PATH"

. "$HOME/.snotes/config" || die "config ~/.snotes/config messed up"

if [ "${SNOTES_CLEANUP}" = "yes" ] && ! type perl >/dev/null 2>&1; then
    info "cleanup mode requires perl"
    SNOTES_CLEANUP="no"
fi

[ -n "$1" ] || die "nothing to do"

cd "${SNOTES_DB}"

unset snotes_file
unset snotes_file_flags

blame(){
    local tmp
    tmp="`newtemp`"
    git blame --relative-date -- "$1" | sed 's/^\^\?/commit:/' > "$tmp"
    chmod 0400 "$tmp"
    snotes_file="$tmp"
    snotes_file_flags=temp
}

commit(){
    local tmp
    tmp="`newtemp`"
    git show --color=never "$1" > "$tmp"
    chmod 0400 "$tmp"
    snotes_file="$tmp"
    snotes_file_flags=temp
}

changed(){
    local tmp
    local diffcommit
    tmp="`newtemp`"

    diffcommit="`git log --oneline --color=never --max-count=${SNOTES_CHANGED_COMMITS} -- \"$1\" | tail -n1 | cut -d' ' -f1`"
    git diff --color=never "${diffcommit}^" -- "$1" > "$tmp"
    chmod 0400 "$tmp"
    snotes_file="$tmp"
    snotes_file_flags=temp
}

cleanup(){
    local tmp
    tmp=`newtemp`

    # cleanup
    cat "$1" | perl -e '
while(<>){
    next if(/^[ \t\n]*$/);
    last;
}
my $tmp="";
do {
    s/^(.*?)[ \t\n]*$/\1/;
    if(/^[ \t\n]*$/){ $tmp= $tmp."\n" }
    else { print $tmp.$_."\n"; $tmp="" };
} while(<>);' > "$tmp"
    cat "$tmp" > "$1"
    rm "$tmp"
}

case "${1%:*}" in
note)
    snotes_file="${1##*:}"
    if [ ! -f "$snotes_file" ]; then
        touch "$snotes_file" && snotes_file_flags=created || die "could not create file '`pwd`/$snotes_file'"
    fi
    ;;
blame)
    blame "${1##*:}"
    ;;
commit)
    commit "${1##*:}"
    ;;
changed)
    changed "${1##*:}"
    ;;
*)
    die "unknown prefix '${1%:*}'"
    ;;
esac

${SNOTES_EDITOR} "$snotes_file"

if [ "${SNOTES_CLEANUP}" = "yes" -a "$snotes_file_flags" != "temp" ]; then
    cleanup "$snotes_file"
fi

[ ! -s "$snotes_file" -a -z "$snotes_file_flags" ] && snotes_file_flags=deleted

case "$snotes_file_flags" in
created)
    if [ -s "$snotes_file" ]; then
        git add -- "$snotes_file"
        git commit -q -m "created note '$snotes_file'"
    else
        rm -f "$snotes_file"
    fi
    ;;
temp)
    rm -f "$snotes_file"
    ;;
deleted)
    git rm -q -f -- "$snotes_file"
    git commit -q -m "removed note '$snotes_file'"
    ;;
*)
    if ! git diff --quiet -- "$snotes_file"; then
        git add -- "$snotes_file"
        git commit -q -m "changed note '$snotes_file'"
    fi
    ;;
esac
