summaryrefslogtreecommitdiff
path: root/src/util/hbar.sh
blob: 603f66a233ed72e083362dd22303db6a4cacc271 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/bin/sh
. /usr/lib/colors.sh
. /usr/lib/xilib.sh

move_up () {
    [ ! "$1" = "-1" ] &&
        printf "\033[%dA" "$1" "0"
}

move_down () {
    [ ! "$1" = "-1" ] &&
        printf "\033[%dB" "$1"
}

count_string () {
    local c t
    $human && {
        c=$(format_bytes $completed)
        t=$(format_bytes $total)
    } || {
        c=$1
        t=$2
    }
    printf "[%s%s/%s%s]" $c $unit $t $unit
}

hbar () {
    local width terminate human text color reset unit line count
    width=$(tput cols)
    color="$BLACK$BG_WHITE"
    reset="$WHITE$BG_DEFAULT"
    terminate=false
    human=false
    line=0

    while getopts "T:c:r:u:l:ht" opt; do
       case "$opt" in
           T)
               text="$OPTARG"
               ;;
           c)
               color="$OPTARG"
               ;;
           r)
               reset="$OPTARG"
               ;;
           u)
               unit="$OPTARG"
               ;;
           t)
               terminate=true
               ;;
           h)
               human=true
               ;;
           l)
               line="$OPTARG"
               ;;
       esac
    done
    shift $((OPTIND-1))

    [ "$#" -lt 2 ] && {
       printf "$RESET\n"
       exit 1
    }

    completed="$1"
    total="$2"

    move_up $line

    count=$(count_string $completed $total)
    printf "\r$text"
    printf "$RESET\r"
    printf "$color"
    
    reset_at=0
    [ "$total" -gt "0" ] && reset_at=$(((completed*width)/total))

    i=0
    while [ "$i" -lt "$width" ]; do 
        [ "$i" = "$reset_at" ] && printf "$reset"

        [ "${#text}" -gt 0 ] && {
            printf "%s" "${text%%${text#?}}"
            text="${text#?}"
        } || {
            printf " "
        }
        i=$((i+1))
    done

    move_down $line

    $terminate && printf "$RESET\n"

    exit 0
}

printf "%s" "$(hbar "$@")"