#!/bin/bash
#
# spinner
# Author: Shawn Alverson
# Created: 09/29/2013
# Modified:
# 
# Description: Creates waiting message and spin box
#              while another process runs.
# Usage: Execute spinner in a seperate script and keep
#        the PID. Disown processreq to suppress terminal
#        alerts. When process is finished, kill spinner
#        and send stdout to /dev/null.
#

# Initialize variables
DELAY=0.7           # Pause between each frame of animation
SPN="|/-\\"         # Animation frame array.  First \ is escape character
LIM=120             # Max limit on repetitions (avoids infinite loop)

# Find Parent PID
SPIN_ID=${1:-$$}
STAT=($(</proc/${SPIN_ID}/stat))
PARENT=${STAT[3]}

# Cleaup operations
function on_exit() 
{
    tput el         # Clear to end of line just to make sure we didn't miss anything
    tput el1        # Clear to beginning of line
    tput cnorm      # Make cursor visible again
    exit 0
}

trap on_exit EXIT                              # Cleanup text and cursor on exit command
printf "Processing request, please wait...["
tput civis                                     # make cursor invisible

for ((i=0; i <= LIM; i++))
do
    FRAME="$(echo "$SPN" | head -c 1)"         # Current animation frame
    printf "%c]" "$FRAME"
    SPN=$(echo "$SPN" | tail -c 4)"$FRAME"     # Cycle current frame to end of array
    sleep $DELAY
    printf "\b\b"                              # Overwrite spinner
    if [ ! -d /proc/$PARENT ]; then break; fi  # Check if parent process is still runnning
done

exit 0