aboutsummaryrefslogtreecommitdiffstats
path: root/functions.sh
blob: 20bb8718f662ace54ee6a6aef763a10c07b1d16c (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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/bin/bash
#set -e

download()
{
    tput civis
    local url=$1
    printf "%b" "${IWHT}    "
    wget -nc -q --show-progress --progress=dot "$url" 2>&1 | grep --line-buffered "%" | \
        sed -u -e "s,\.,,g" | awk '{printf("\b\b\b\b%4s", $2)}'
	local retval="${PIPESTATUS[0]}"
	if [[ "${retval}" -ne 0 ]]; then
		printf "%b" "${RED}FAILED! WGET EXIT (${retval})\n${RST}"
		exit "${retval}"
	fi
    tput cnorm
}

export -f download

# Shows a spinner while another command is running. Randomly picks one of 12 spinner styles.
# @args command to run (with any parameters) while showing a spinner.
#       E.g. ‹spinner sleep 10›

function cursorBack() {
  echo -en "\033[$1D"
}

function spinner() {
  # make sure we use non-unicode character type locale
  # (that way it works for any locale as long as the font supports the characters)
  local numspinners=12

  local LC_CTYPE=C

  local pid=$1 # Process Id of the previous running command

  local spintype=$2

  if [[ -z "${spintype}" ]] || [[ "${spintype}" -ge "${numspinners}" ]]; then
	  spintype=$((RANDOM % numspinners))
  fi

  case "${spintype}" in
  0)
	local spin='-\|/'
    local charwidth=1
    ;;
  1)
    local spin='.oO0Oo'
    local charwidth=1
    ;;
  2)
	local spin='⠁⠂⠄⡀⢀⠠⠐⠈'
    local charwidth=3
    ;;
  3)
    local spin="▁▂▃▄▅▆▇█▇▆▅▄▃▂▁"
    local charwidth=3
    ;;
  4)
    local spin="▉▊▋▌▍▎▏▎▍▌▋▊▉"
    local charwidth=3
    ;;
  5)
    local spin='←↖↑↗→↘↓↙'
    local charwidth=3
    ;;
  6)
    local spin='▖▘▝▗'
    local charwidth=3
    ;;
  7)
    local spin='┤┘┴└├┌┬┐'
    local charwidth=3
    ;;
  8)
    local spin='◢◣◤◥'
    local charwidth=3
    ;;
  9)
    local spin='◰◳◲◱'
    local charwidth=3
    ;;
  10)
    local spin='◴◷◶◵'
    local charwidth=3
    ;;
  11)
    local spin='◐◓◑◒'
    local charwidth=3
    ;;
  12)
    local spin='⣾⣽⣻⢿⡿⣟⣯⣷'
    local charwidth=3
    ;;
  esac

  local i=0
  tput civis # cursor invisible
  tput bold setaf 7
  while kill -0 "$pid" 2>/dev/null; do
    local i=$(((i + charwidth) % ${#spin}))
    printf "%b" "${spin:$i:$charwidth}"

    cursorBack 1
    sleep .2
  done
  tput cnorm
  wait "$pid" # capture exit code
  return $?
}

fail()
{
	printf "%b" "${IRED}${1}${RST}\n"
}
export -f fail

success()
{
	printf "%b" "${IGRN}${1}${RST}\n"
}
export -f success