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


waiter(){
    local is_newline_put
    # watcher of the command, with space after the command, of course
    #while ps aux | grep -v grep | grep -v "$$" | grep -v "$(basename $0) $watcher" | grep -vE "(vim|gvim|emacs|scite|geany).*${watcher}" | grep -qE "([[:digit:]] ${watcher} |[[:digit:]] ${watcher}$|[[:digit:]] .*bin/${watcher} |[[:digit:]] .*bin/${watcher}$)"
    while pidof -zcxq "$watcher" 2>/dev/null
    # warning: next command cuts the 'command' name if is longer than 15 chars, so it cannot work with these ones
    #while ps axk comm o comm,args | grep -qs "^${watcher}.*${watcher} "
    do
        # put a new line
        if ! ((is_newline_put)) ; then
            echo -e ""
            is_newline_put=1
        fi

        is_waiting=1

        if [[ "${counter}" -gt "60" ]] ; then
            minutes="$(( $counter / 60 ))"
        fi

        if [[ -n "$minutes" ]] ; then
            echo -en "\r\033[KProcess ${watcher} still running, waiting... [$minutes minutes]     "
        else
            echo -en "\r\033[KProcess ${watcher} still running, waiting... [$counter seconds]     "
        fi


        sleep ${check_delay}
        counter="$(( $counter + ${check_delay} ))"
    done

}

main(){
    # pre {{{
    if [[ ! -t 0 ]] ; then
        is_stdin=1
    fi

    # }}}
    # show help if no parameters
    if [[ -z "$1" ]] && ! ((is_stdin)) ; then
        #el_explain 0 "Usage: __$(basename $0)__ XXwatchingXX command-to-run and parameters"
        el_explain 0 "Usage: __$(basename $0)__ XXwatchingXX && another-command"
        el_explain 0 "Waits for another process to finish before to continue (exits), so it can be used to run commands after others has finished"
        el_explain 0 "Details: only one word should be given as process to watch, the process needs to match a simple __ps aux__"
        el_explain 0 "Example: run in a terminal 'sleep 10', and in another 'waitfor sleep && echo all sleeps finished'"
        exit 1
    fi
    if [[ -n "$2" ]] ; then
        el_error "use it only with one argument"
        exit 1
    fi

    # variables
    watcher="$1"
    shift
    check_delay="4"

    counter=0

    waiter
    # if process were waiting, make a pause first and verify it again
    if ((is_waiting)) ; then
        sleep 3
        waiter
    fi
    # run our command
    # "$@"

    # ready for run our command, simply exit
    return 0

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
