#!/usr/bin/env bash
#
# spinner - display a spinner for long running commands
# (this script leaves no trail of the spinner at finishing)
#
# usage:
#       spinner [long-running-command]

# tl;dr
# `stdout` will be whatever the output of your command is and
# `stderr` will be the spinner spinning around round oud und nd d
# so you can pipe stuff without problem (:

# see: https://gist.github.com/nicknisi/a26f148611517e3d998eb456ac57efff#file-new-worktree-sh-L76-L96

# shellcheck shell=bash disable=SC2312

# execute your stuffs in a background job
eval "${@:-sleep 1}" &

# point fd#3 to fd#1 (save it for later use), then point fd#1 to fd#2
# pd: this does not interfere with the variable for the PID i.e. $!
exec 3>&1 >&2

PID=$!
# SPINNER_PARTS="/-\|"
# SPINNER_PARTS="⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
# see: https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json
SPINNER_PARTS="⣾⣽⣻⢿⡿⣟⣯⣷"
SPINNER_PARTS="⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
ACC=1

printf " "
while ps a | awk '{ print $1 }' | grep -q "${PID}"; do
  printf "\b%s" "${SPINNER_PARTS:ACC++%${#SPINNER_PARTS}:1}"
  sleep .15
done
printf "\b"

exec >&3 3>&-
