#! /bin/ksh
#! /bin/sh
#! /bin/bash

# Percentage bar for some of the most common shells
# Copyright (C) 2009 Matous Jan Fialka, <http://mjf.cz/>
# Released under the terms of The MIT License

BAR_WIDTH=${BAR_WIDTH:-72}

bar()
{
	pct=$(( ${1:-0} * 100 / ${2:-100} ))
	chr=$(( ${1:-0} * ( BAR_WIDTH - 7 - ${#3} ) / ${2:-100} ))
	inx=0

	prn="$3"

	if (( pct >= 100 && ${#4} > 0 ))
	then
		printf "\033[2K%s%s\033[%dD" "$prn" "$4" $(( ${#4} + ${#prn} + 1 ))
		return
	fi

	prn="$prn|"

	while (( inx < chr ))
	do
	        prn="$prn*"
	        (( ++inx ))
	done

	inx=0

	while (( inx < BAR_WIDTH - 7 - ${#3} - chr ))
	do
	        prn="$prn "
	        (( ++inx ))
	done

	printf -- '%s| % 3s%%\033[%dD' "$prn" $pct $BAR_WIDTH
}



# Demo usage

for a in string very-long-string long-string
do
	c=$(( RANDOM % 20 + 1))
	i=$c

	while (( i >= 0 ))
	do
	        bar $(( i-- )) $c "Testing $a " '... PASSED'
	        sleep 0.$(( RANDOM % 4 ))
	done

	sleep 0.5

	c=$(( RANDOM % 20 + 1))
	i=0

	while (( i <= c ))
	do
	        bar $(( i++ )) $c "Testing $a " '... PASSED'
	        sleep 0.$(( RANDOM % 4 ))
	done

	sleep 0.5

	c=$(( RANDOM % 50 + 1 ))
	i=0

	while (( i <= c ))
	do
	        bar $(( i++ )) $c "Proceeding $a " '... OK'
	        sleep 0.$(( RANDOM % 4 ))
	done
	echo

	sleep 0.5
done
