#!/bin/bash

#
# compile
# v0.2, August 2003
#
# Displays the progress, speed and estimated remaining time of a compilation.
# Use instead of "make". The make command is invoked by the script.
# The script counts the number of source file and the number of objects and
# measures the time of making source files to object files.
# Because sometimes not all source files need to be compiled this is only an
# approximate value.
# The program stops when the make process has quit.
#
# Copyright (c) 2003 Stephan Uhlmann <su@su2.info>
# 
# /************************************************************************
# * This program is free software; you can redistribute it and/or modify  *
# * it under the terms of the GNU General Public License as published by  *
# * the Free Software Foundation; either version 2 of the License, or     *
# * (at your option) any later version.                                   *
# *                                                                       *
# * See http://www.fsf.org/copyleft/gpl.txt for the full text of the GPL. *
# ************************************************************************/
#

term_reset()
{
	tput sc
	tput csr 0 $(($LINES-1))
	tput rc
}

clear
LINES=`tput lines`
tput csr 4 $(($LINES-1))
trap term_reset SIGINT
tput cup 4 0

NUMSRC=$((`find -type f -name "*.c" -o -name "*.cpp" -o -name "*.cc" | wc -l`))
if (test $NUMSRC -eq 0); then echo "No source files found."; exit 1; fi
NUMOBJSTART=$((`find -type f -name "*.o" | wc -l`))
STARTDATE=$((`date +%s`))

(make) &
MAKEPID=$!

while [ -d /proc/$MAKEPID ];
do
	# some source files are generated while compiling
	NUMSRC=$((`find -type f -name "*.c" -o -name "*.cpp" -o -name "*.cc" | wc -l`))
	NUMOBJ=$((`find -type f -name "*.o" | wc -l`))
	CURRENTDATE=$((`date +%s`))
	DIFFTIME=$(($CURRENTDATE-$STARTDATE))
	if (test $DIFFTIME -eq 0); then DIFFTIME=1; fi
	DIFFOBJ=$(($NUMOBJ-$NUMOBJSTART))
	if (test $DIFFOBJ -eq 0); then DIFFOBJ=1; fi

	tput sc
	tput cup 0 0
	tput el
	echo "Progress: $(($NUMOBJ*100/$NUMSRC))% ($NUMOBJ/$NUMSRC) finished."
	I=`echo "scale=2; ($NUMOBJ-$NUMOBJSTART)/$DIFFTIME" | bc`
	tput el
	echo "Speed:    $I Objects/s."
	I=$(((($NUMSRC-$NUMOBJ)*$DIFFTIME)/$DIFFOBJ))
	tput el
	echo "Wait:     $(($I/60)) Min $(($I%60)) Sec"
	tput el
	echo
	tput rc

	sleep 2

done

term_reset

