#!/bin/sh -fu

. etcgit-sh-functions

write_error() {
        echo "$@" >&2
}

if [ $# -eq 0 ]; then
        if [ -n "$(_list_modified)" ]; then
                echo -e "$(get_branch_head)+\\t$(get_branch_name)\\t$(get_head_message)"
                exit 1
        else
                echo -e "$(get_branch_head)\\t$(get_branch_name)\\t$(get_head_message)"
                exit 0
        fi
else
        CMD="$1"; shift
        case "$CMD" in
                head)
                        if [ -n "$(_list_modified)" ]; then
                                echo "$(get_branch_head)+"
                        else
                                echo "$(get_branch_head)"
                        fi
                        ;;
                diff)
                        if [ $# -gt 0 ]; then
                                get_diff "$1"
                        else
                                get_diff
                        fi
			;;
		branch)
                        if [ $# -gt 0 ]; then
                                list_remote_branches "$1"
                        else
                                list_local_branches
                        fi
                        ;;
                log)
                        in_limit="$(echo $* | sed -n -e 's/^.*-\([0-9]\+\).*$/\1/p')"
                        list_commits
                        ;;
                services)
                        list_start_seq
                        ;;
                status)
                        _list_modified
                        ;;
                fetch)
                        if [ $# -gt 1 ]; then
                                url="$1"
                                hd="$2"
                                br="$(remote_branch_for_head "$url" "$hd")"
                                fetch_remote_branch "$url" "$br"
                        elif [ $# -gt 0 ]; then
                                hd="$1"
                                br="$(local_branch_for_head "$hd")"
                                delete_branch "$br"
                        fi
                        ;;
                checkout)
                        if [ $# -gt 0 ]; then
                                hd="$1"
                                br="$(local_branch_for_head "$hd")"
                                reload_branch "$br"
                        fi
                        ;;
                checkout-meta)
                        if [ $# -gt 0 ]; then
                                hd="$1"
                                br="$(local_branch_for_head "$hd")"
                                checkout_meta "$br"
                        fi
                        ;;
                switch)
                        cat <<EOF | at now 2>/dev/null
$0 fetch "$1" "$2" && $0 checkout "$2"
EOF
                        ;;
        esac
fi
