#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
#EL_REPORTS="1"
#el_make_environment


main(){
    # pre {{{
    local message result arg

    for arg in "$@" ; do
        case $arg in
            -p|--push)
                shift
                is_push=1
                ;;
            -m|--message)
                shift
                message="$1"
                shift
                ;;
        esac
    done
    # }}}

    command git --no-pager diff
    command git status

    if [[ -z "$message" ]] ; then
        if [[ -n "$1" ]] ; then
            message="$@"
        else
            echo -e ""
            echo -e "Going to commit everything listed, press ^C for cancel"
            echo -e "Message?"
            read -e message
        fi
    fi


    command git commit -am "$message"

    if ((is_push)) || el_confirm "Push now?" ; then

        result="$( LC_ALL=C command git push 2>&1 | grep -Fv "Warning: Permanently added" )"
        echo "$result"
        echo ""

        # bad connection, try again
        if echo "$result" | grep -Fqs "Could not resolve hostname" ; then
            sleep 2
            result="$( LC_ALL=C command git push 2>&1 | grep -Fv "Warning: Permanently added" )"
            echo "$result"
            echo ""
            el_error "failed connection, try again?"
        fi

        # nothing added?
        if echo "$result" | grep -Fqs "Everything up-to-date" ; then
            el_error "nothing pushed"
        fi

        # pushed correctly
        if echo "$result" | grep -qs "\.\..*-> " ; then
            el_info "pushed"
        fi

        if LC_ALL=C command git status 2>&1 | grep -Fqs "Untracked files" ; then
            command git status
            echo ""
            el_warning "Untracked files remaining"
        fi
    else
        echo ""
    fi

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
