#!/bin/bash

# Usual commands
DVIPS=dvips
LATEX=latex
SCILAB=scilab
TAR=tar
UNRAR=unrar
UNZIP=unzip

# List of possible extensions 
ZIPEXT="tar|tgz|tar.gz|rar|zip";
TEXEXT="tex";
DVIEXT="dvi";
REPEXT="ps|pdf";
SCIEXT="sci";
OTHEXT="eps"; # Not currently handled 
DELEXT="log|dvi|aux"; # Clean up 

# Global variables
SCIFILE="_._sci";
ERRFILE="_._err";
NUMERR="0";

# Find the package file and unpack it
function unpack {
    cd $1; 
    echo -n "Looking for archive file in $1 : "; 
    IFS=$'\n'
    FILE=$(ls | egrep "[^\.]*\.($ZIPEXT)$")
    NUMF=$(echo $FILE | wc -w)
    echo $NUMF file found
    local F=;
    for F in $FILE; do
	echo -n "Handling $F ";
	case $F in 
	    *.tar)
		echo -n "(Tar format)";
		$TAR xf $F;
		if [ $? -ne 0 ]
		    then echo " Error unpacking archive" && exit 1;
		fi
		;;
	    *.tar.gz)
		echo -n "(Tar.gz format)";
		$TAR xzf $F ;
		if [ $? -ne 0 ]
		    then echo " Error unpacking archive" && exit 1;
		fi
		;;
	    *.tgz)
		echo -n "(Tgz format)";
		$TAR xzf $F;
		if [ $? -ne 0 ]
		    then echo " Error unpacking archive" && exit 1;
		fi
		;;
	    *.rar)
		echo -n "(Rar format)";
		$UNRAR -inul -o+ e $F;
		if [ $? -ne 0 ]
		    then echo " Error unpacking archive" && exit 1;
		fi
		;;
	    *.zip)
		echo -n "(Zip format)";
		$UNZIP -o -q $F;
		if [ $? -ne 0 ]
		    then exit 1;
		fi
		;;
	    *) 
		echo "- File extension not handled, exiting ...";
		exit 1;
		;;
	esac
	if [ $? -eq 0 ]
	    then echo " ok.."
	fi
    done
    cd ..
}

# Restore all files in the main directory 
function flatten_rec {
    if [ -d $1 ]
	then 
	cd $1; 
	local LIST=$(ls);
	local F=;
	for F in $LIST; do 
	    if [ -d $F ]
		then
		flatten_rec $F;
		mv $F/* ./;
		rm -rf $F;
	    fi
	done;
	cd ..;
    fi
}
function flatten {
    echo -n "Flattening $1 into single directory ";
    cd $1;
    local F=;
    for F in $(ls); do 
	if [ -d $F ]
	    then
	    flatten_rec $F;
	    mv $F/* .;
	    rm -fr $F;
	fi
    done
    cd ..;
    echo "ok..";
}

# Clean all non-archive files in the given directories
# and cleans directory itself if it finishes empty
function clean_force {
    cd $1;
    FILE=$(ls | egrep -v "[^\.]*\.($ZIPEXT)$");
    local F=;
    for F in $FILE; do
	echo "Cleaning $F";
	if [ -d "$F" ] 
	    then 
	    rm -rf "$F";
	else
	    rm -f "$F"; 
	fi	    
    done
    cd ..;
    TEST_EMPTY=$(ls $1 | wc -l)
    if [ $TEST_EMPTY -eq 0 ]
	then rmdir $1;
    fi
}

# Function to compile a tex file 
function compile_tex_file {
    echo "- $1 -> ${1%.tex}.dvi"
    $LATEX -interaction=nonstopmode $1 > /dev/null;
    if [ $? -ne 0 ] 
	then echo "(Latex failed) "; 
    fi
}

# Function to compile a dvi file 
function compile_dvi_file {
    echo "- $1 -> ${1%.dvi}.ps"
    $DVIPS $1 -o -q 2> $ERRFILE;
    if [ $? -ne 0 ]
	then echo "(Dvips failed) ";
    fi
    if [ $(cat $ERRFILE | wc -l) -ne 0 ]
	then 
	echo -n "(Dvips had problems) ";
    fi
    rm -f $ERRFILE;
}

# Find the report file inside the directory, and
# compiles it if not present.
function handle_report {
    echo "Handling report in $D : ";
    cd $D; 
    REP=$(ls | egrep "[^\.]*\.($REPEXT)$");
    NREP=$(echo $REP | wc -w);
    if [ $NREP -ge 2 ] 
	then 
	echo "Too many possible reports : $REP";
	#exit 1;
    else
	if [ $NREP -eq 0 ] 
	    # No report has been found
	    then 
	    # Is there a tex file ? 
	    TEX=$(ls | egrep "[^\.]*\.($TEXEXT)$");
	    NTEX=$(echo $TEX | wc -w);
	    if [ $NTEX -ge 1 ] 
		then 
		local TTEX=;
		for TTEX in $TEX;
		  do 
		  compile_tex_file $TTEX;
		done
	    fi
	    # Is there a dvi file ? 
	    DVI=$(ls | egrep "[^\.]*\.($DVIEXT)$");
	    NDVI=$(echo $DVI | wc -w);
	    if [ $NDVI -ge 1 ] 
		then 
		local TDVI=;
		for TDVI in $DVI;
		  do 
		  compile_dvi_file $TDVI;
		done
	    else
		echo "No valid tex or dvi file found"; 
		    #exit 1;
	    fi
	else
	    # The report has been found
	    echo "- $REP";
	fi
	if [ -z "$REP" ]
	    then  NUMERR=$(echo "$NUMERR+1" | bc);		
	fi; 
    fi
    cd ..;
}

# Handle sci files, executes them to test whether they compile
# in a valid way, and the "load" are exact
function handle_scifiles {
    echo "Handling sci files in $1 :";
    cd $1; 
    SFILE=$(ls | egrep "[^\.]*\.($SCIEXT)$")
    for F in $SFILE; 
      do
      echo -n "- $F ";
      echo "errcatch(-1,'stop'); mode(-1); exec('$F',-1); quit;" > $SCIFILE
      EXEC=$(echo "\n\n\n\n" | $SCILAB -nb -nw -f $SCIFILE | grep error | wc -l); 
      if [ $EXEC -eq 0 ]
	  then 
	  echo "ok..";
      else
	  echo "(Scilab found errors)";
	  NUMERR=$(echo "$NUMERR+1" | bc);
      fi
    done
    rm -f $SCIFILE;
    cd ..;
}

# Clean up final directories
function clean_up {
    cd $1; 
    DFILE=$(ls | egrep "[^\.]*\.($DELEXT)$");
    rm -f $DFILE;
    cd ..
}

# Parsing arguments
DIRECTORIES=
while [ $# -gt 0 ]
do
  case $1 in 
    -c)
	echo "Clean directories mode";
	CLEAN_MODE=1;;
      *)
	  if [ -d $1 ]
	      then
	      DIRECTORIES="$1 $DIRECTORIES"
	  fi
	  ;;
  esac
  shift;
done

# Main part of the script
if [ $CLEAN_MODE ]
    then
    for D in $DIRECTORIES; do
	clean_force $D;
    done
else
    echo "Normal mode";
    for D in $DIRECTORIES; do
	echo "------";
	unpack $D;
        flatten $D;
	handle_report $D;
	handle_scifiles $D;
	clean_up $D;
    done
    echo "------";
    echo "Error(s) found : $NUMERR";
fi

