#!/bin/bash

# Waits for MacPorts to finish what it's doing, then exits.

PORT_TCLSH="$(which port-tclsh 2>&1)"
PORT_TCLSH="$(readlink "$PORT_TCLSH" || echo "$PORT_TCLSH")"

if [ ! -x "$PORT_TCLSH" ]; then
    echo "port-tclsh command not found" 1>&2
    exit 1
fi

PROGRESS_CHARS="/-\\|"
PROGRESS_INDEX=0
MESSAGE="Waiting for MacPorts to finish what it's doing... "

cleanup() {
    printf "\r%${#MESSAGE}s   \r"
    tput cnorm
    exit 0
}

trap cleanup INT
tput civis
while [ -n "$(ps aww | grep "$PORT_TCLSH" | grep -v grep)" ]; do
    printf "\r${MESSAGE}${PROGRESS_CHARS:$PROGRESS_INDEX:1}"
    PROGRESS_INDEX=$((($PROGRESS_INDEX + 1) % ${#PROGRESS_CHARS}))
    sleep 1
done
cleanup
