#!/bin/sh
#$Header: /home/gio/CVSREPOSITORY/egServer/egServer,v 1.3 2000/05/27 16:00:12 gio Exp $
#$Revision: 1.3 $
#$Id: egServer,v 1.3 2000/05/27 16:00:12 gio Exp $

#  Flusso di esecuzione:
#  1 Il .forward manda ogni singola mail ad un processo, che esegue
#  egServerSvaglia
#  2 egServerSveglia esegue veloce veloce un cat dell' input in un file temporaneo.
#    (solitamente ~/egServer/serverTMP)
#  3 egServerSveglia, invoca un processo egServer dando come primp parametro il nome
#  del file che contiene l'email.
#  4 egServer riceve quindi in $1 il nome del file temporaneo usato da egServerSveglia
#  Per queste ragioni, per eseguire il debug del server "basta" mandargli 
#  in input una email...
#  5 al ritorno, egServerSveglia cancella le tracce del suo file temporaneo
#  ma solo se il debug lo richiede

############################################################
# @BUGS: Se $1  nullo si comporta come un cipplone
# Fragile, inserire un engine di auto-diagnostica e testing
# 

# Var usate dallo script
# I commenti subito seguiti da 
# ** sono modificabili dall' amministratore del Server...
#Home dir del server (in toeira basta spostare questa per ridefinire tutti 
#gli altri percorsi relativi).
serverHomeDir=/home/gio/egServer
source $serverHomeDir/egServerIni.sh


# File temporaneo usato per processare la mail
#In particolare il file tiene la(e) linea(e) che contengono la password
#Se esiste pi di una linea con la password, le successive sono ignorate.
lineWithData=$workDir/lines.with.password.$tmpSuffix
linebuffer=$lineWithData.linebuffer

#Input: File name da processare
#obj=$1
obj=${1:-FurboneNonFileDefinitoE}
if([ ! -e $obj ]) then
    echo -en "\\033[1;31m"
    echo -en "[ ERROR ]"
    echo Error, file do not exist or no file-name provided
    echo as first parameter
    echo -e "\\033[1;32m"
    echo Usage is simple but not trivial:
    echo $0 emailToProcess
    echo -e "\\033[1;39m"
    exit 123
fi

function emerengyExit()
{
    #Se siamo qui abbiamo avuto molta ma molta
    #sfiga...proviamo a dirlo e basta
    tmp=/tmp/$$.egServerFatalError
    echo "Errore fatale! tmpSuffix vale $tmpSuffix " | mail -s "egServer FATAL ERROR on $dataAttuale "$reportAddr
}

trap emergencyExit SIGTERM SIGILL SIGUSR1 SIGKILL

#Funzione di filtro:
#In caso di errore esce.
#NB: alcuni url sono particolarmente coriacei e potrebbero essere innocui ma
# fallire questi scemplici test.
# Come al solito, bisogna o milgiorare i test, o abbattere la sicurezza...
function securityCheck()
{
    linea=$1
    if (test $debug = yes) then
	echo "Entered in  securityCheck for $linea"
    fi

    if (echo $linea | grep "\;" ) then
	echo "Not Safe the ; usage, Aborted"
	exit 1;
	else
	    if (echo $linea | grep "&&" )  then
		echo "Not Safe the double and usage, Aborted."
		exit 1; 
	    fi
    fi
    echo "Secure (in my own opinion of course)"
}

# Formato delle linee:
#   passcom#http://......
#

####### Iniza l' esecuzione da qui

echo "-------- egServer [STARTED] --------------------------"
echo "----- Version $egServerVersion $egServerVersionId --------"
echo "di Giovanni Daitan  Giorgi...miii speriamo che funzioni "
echo "--------------------------------------------------------"

echo "Processing $obj received " `date` 
echo Email info:
# Stampa From & Subject....
echo `grep From $obj`
echo `grep Subject $obj`
echo Checking if password is present....

# Processa il file $obj
if (grep $passcom $obj >$lineWithData) then
    #Formato: 
    #   #PASSCOM#EMAIL#http://....file...html
    #Ora estraggo il parametro che si trova in terza posizione
    cut -f 3 -d# $lineWithData >$linebuffer ;
    echo " Command list is " ;
    echo " ->" `cat $linebuffer` ;
    #Ora in tmp2 ho al piu' una lista di url da ricercare....
    #Estraggo solo il primo
    url=`tail -n +0 $linebuffer`
    
    #** Programma da usare per il recupero dell' url
    com="$wgetCommand -c $url"
    echo Checking line 
    echo "->"$com"<-"
    echo for Cracking Tryers...
    securityCheck "$com"
    echo Ok...proceeding...
    #Da killare con delicatezza


	# Estraggo l' indirizzo di email
	email_dest=`cut -f 2 -d# $lineWithData`
	#** Volendo qui si potrebbe costruire un filtro per evitare 
        # indirizzi "indesiderati"
	# Per es. indirizzi da iname.com o hotmail.com
	
	tempDownLoadDir="$egServerDownLoadDir/$email_dest.$$"
	echo -n Building Temp dir named:  $tempDownLoadDir ...
	mkdir $tempDownLoadDir || (echo Error and aborting; exit 2)
	echo OK

	#   egServer invia due email:
	#  La prima quando il comando (wget) parte, mentre la 
	#  Seconda alla fine dell'esecuzione.
	#   Questo perch un fetching pu richiedere parecchio tempo e sarebbe
	#  pericoloso aspettare fino alla fine per inviare un report.
	# Crea il mail report
	reportFile=$tempDownLoadDir/Report.$$
	echo "Utente: $email_dest" > $reportFile
	echo "Richiesta di Tipo: WGET" >> $reportFile
	echo "Linea di comando: $com" >> $reportFile
	echo "Data:" `date` >> $reportFile
	echo "Segue Header email ricevuta:" >>$reportFile
	echo "___________________________________________________" >>$reportFile
	cat $obj >> $reportFile
	echo "___________________________________________________" >>$reportFile

	
	echo "Ok...Sending Report Mail (the report is in temp file $reportFile)"
		

	#  Invia la PRIMA email	
	#BUG: Chi cancella sto povero file?
	cat $reportFile | mail -s egServer_Started $reportAddr  
	echo ".....Fetch command Running....."
	(cd $tempDownLoadDir ; $com  1>$commandLog 2>&1 )
	if (test $debug = yes) then
	    echo DEBUG: Wget output is
	    cat $commandLog
	fi
	#Ora deve spedire il contenuto all' indirizzo e-mail:
	
	#Comprime tutti i file scaricati:
	echo "Zipping Files..."
	fileArchiviatoEScaricato=$egServerDownLoadDir/downloaded.$dataAttuale.zip
	# -m implica il move
	# NB: il report viene inglobato nello zip, proprio per fornire al
	# nostro richiedente un buion servizio...
	(cd $tempDownLoadDir &&  zip -mr0 $fileArchiviatoEScaricato *)
	
	
	#Per spedire l' email encodata con il dato metodo alternativo:
	#uuencode  $fileArchiviatoEScaricato  | mailx -s 'subj' $emailDest
	
	#Spedisce la seconda email.
	#Per prima cosa prepara un file temporaneo con un bel report:
	reportFile2=$tempDownLoadDir/ReportPerAmministratore.$$	
	cat >$reportFile2 <<EOFGIO
	_______________________________________________________________
	egServer Informa Signoria Vostra che  stata portato a termine
	una richiesta di download
  Dettagli:
    Contenuto dello zip archiviato:
EOFGIO
	echo -n Sending II report email to administrator..
	unzip -v $fileArchiviatoEScaricato >>$reportFile2
	echo >>$reportFile2 &&	echo "Log del comando ->$com<- eseguito:" >>$reportFile2 && 	echo >>$reportFile2 

	echo -n "..ing.."

	cat $commandLog >>$reportFile2

	cat $reportFile2 | mail -s "egS_log_for $com" $reportAddr
	echo .ok
	
	
	#
	#** Durante i test non cancello i files temporanei
    if (test $debug = no) then
	echo -n "Removing temp files..."
        rm $commandLog
	rm $lineWithData $linebuffer   $reportFile2
        echo -n "....temp dir..."       
	# *** Da commentare durante i test...
	rm -r $tempDownLoadDir
	echo "Done"
	echo "$com Succesful completed"
    else
	echo _____________________________________________
	echo Debug: I will remove 
	echo $commandLog,  $lineWithData, $linebuffer, $reportFile2
	echo and the directory  $tempDownLoadDir
        echo "when no in debug mode"
	echo ---------------------------------------------
    fi
else
    echo Password not found 
    #":("
fi


# Rimuove l' email oramai processata solo se non  in debug
if (test $debug = no) then
    rm $obj || (echo Cannot remove temp email $obj ; exit 2)
else
    echo Debug: I will remove $obj when no in debug mode
fi

