#!/bin/bash source /etc/profile

ANSI_RED=“033[31;1m” ANSI_GREEN=“033[32;1m” ANSI_RESET=“033[0m” ANSI_CLEAR=“033[0K”

FLOW_TEST_RESULT= FLOW_CMD=

flow_cmd() {

local cmd assert output display retry timing result

cmd=$1
FLOW_CMD=$cmd
shift

while true; do
  case "$1" in
    --assert)  assert=true; shift ;;
    --echo)    output=true; shift ;;
    --display) display=$2;  shift 2;;
    --retry)   retry=true;  shift ;;
    --timing)  timing=true; shift ;;
    *) break ;;
  esac
done

if [[ -n "$timing" ]]; then
  flow_time_start
fi

if [[ -n "$output" ]]; then
  echo "\$ ${display:-$cmd}"
fi

if [[ -n "$retry" ]]; then
  flow_retry eval "$cmd"
else
  eval "$cmd"
fi
result=$?

if [[ -n "$timing" ]]; then
  flow_time_finish
fi

if [[ -n "$assert" ]]; then
  flow_assert $result
fi

return $result

}

flow_time_start() {

flow_timer_id=$(printf %08x $(( RANDOM * RANDOM * RANDOM )))
flow_start_time=$(flow_seconds)
echo -en "flow_time:start:$flow_timer_id\r${ANSI_CLEAR}"

}

flow_time_finish() {

local result=$?
flow_end_time=$(flow_seconds)
local duration=$(($flow_end_time-$flow_start_time))
echo -en "flow_time:end:$flow_timer_id:start=$flow_start_time,finish=$flow_end_time,duration=$duration\r${ANSI_CLEAR}"
return $result

}

function flow_seconds() {

local cmd="date"
local format="+%s"
local os=$(uname)

$cmd -u $format

}

flow_retry() {

local result=0
local count=1
while [ $count -le 3 ]; do
  [ $result -ne 0 ] && {
    echo -e "\n${ANSI_RED}The command \"$@\" failed. Retrying, $count of 3.${ANSI_RESET}\n" >&2
  }
  "$@"
  result=$?
  [ $result -eq 0 ] && break
  count=$(($count + 1))
  sleep 1
done

[ $count -gt 3 ] && {
  echo -e "\n${ANSI_RED}The command \"$@\" failed 3 times.${ANSI_RESET}\n" >&2
}

return $result

}

flow_assert() {

local result=${1:-$?}
if [ $result -ne 0 ]; then
  echo -e "\n${ANSI_RED}The command \"$FLOW_CMD\" failed and exited with $result.${ANSI_RESET}\n\nYour build has been stopped."
  flow_terminate 2
fi

}

flow_terminate() {

pkill -9 -P $$ &> /dev/null || true
exit $1

}

flow_fold() {

local action=$1
local name=$2
echo -en "flow_fold:${action}:${name}\r${ANSI_CLEAR}"

}

flow_result() {

local result=$1
export FLOW_TEST_RESULT=$(( ${FLOW_TEST_RESULT:-0} | $(($result != 0)) ))

if [ $result -eq 0 ]; then
  echo -e "\n${ANSI_GREEN}The command \"$FLOW_CMD\" exited with $result.${ANSI_RESET}"
else
  echo -e "\n${ANSI_RED}The command \"$FLOW_CMD\" exited with $result.${ANSI_RESET}"
fi

}

mkdir -p $HOME/build cd $HOME/build

export GIT_ASKPASS=echo