#! /bin/bash

TYPE="empty"
PERIODE="empty"
DATE="`date '+%Y-%m-%d %H:%M:%S'`"
PREURL="http://${DBUSER}:${DBPWD}@localhost:9673/${ZOPEPRODUCT}"
WGET="wget -q -O "
VERBOSE="0"
VERSION=""
DECAL=0
EMAIL=1
GLOBALFILE=""

while true ; do
	case $1 in
	-t)
		TYPE=$2
		shift 2
		;;
	-p)
		PERIODE=$2
		shift 2
		;;
	-v)
		VERBOSE="1"
		shift 1
		;;
	-d) 
		DECAL=$2
		shift 2
		;;
	-n)
		EMAIL=0
		shift 1
		;;
	-h)
		help
		exit 0;
		;;
    -f) GLOBALFILE=$2
		  shift 2
		  ;;
	*)
		break
		;;
  esac
done


if [ -f <CONFIGDIR>/$GLOBALFILE ]
then
	. <CONFIGDIR>/$GLOBALFILE
elif [ -n "$GLOBALFILE" ]
then
	echo "<CONFIGDIR>/$GLOBALFILE introuvable !"
	exit 1
elif [ -f <CONFIGDIR>/globals?*.sh ]
then
	. <CONFIGDIR>/globals?*.sh
else
	. <CONFIGDIR>/globals.sh
fi



error() {
		echo "ERROR: make_rapport.sh: $DATE: $1" 1>&2
		echo "ERROR: make_rapport.sh: $DATE: $1" >> $LOGFILE
}

exec_sql() {
	exec-sql.sh -t 30 -H ${DBHOST} -d ${DBNAME} -u "${DBUSER}" -p "${DBPWD}" -l $LOGFILE -c "$1" | dos2unix -f -- 
	if [ $? -ne 0 ]
		then
		error "cannot execute '$1' on ${DBNAME}@${DBHOST}"
	fi
}

log_message () {
	echo "${DATE} : $1" >> $LOGFILE
}

print_message () {
	if [ $VERBOSE = "1" -o -n "$DEBUG" ]
		then
		echo "[DEBUG] $1"
	fi
}

help () {
	echo "make_rapport_manager -t type -p periode [ -h ] [ -d decalage ] [ -n ]"
	echo ""
	echo " * période in 'hebdo', 'mensuel', 'annuel'"
	echo " * type in 'dg', 'manager', 'commercial', 'assistant' or 'all'"
	echo ""
	echo " -n = no emailing"
	echo " -h = help"
	echo " -d décalage = décale les dates dans le passé, vérifier les dates avec l'option -v avant de lancer !"
	echo " -v = verbose débug mode (rien n'est fait)"
	echo ""
}

reset () {
	echo "$MAILTO" > rapport_mails.lst
	rm -rf rapport_message.html
	can_generate=0
}

base_replace () {
  	replace.sh -r '<SITEINTRAIMAGESDIR>' -s "${INTRAHOST}/${SITEINTRAIMAGESDIR}" -f rapport_message.html
	replace.sh -r '<SITEINTRACSSDIR>' -s "${INTRAHOST}/${SITEINTRACSSDIR}" -f rapport_message.html
	replace.sh -r '<PERIODE>' -s "$PERIODE" -f rapport_message.html
	replace.sh -r '<ZENADDRESS>' -s "${INTRAHOST}/${ZOPEPRODUCT}" -f rapport_message.html
}

case $DEBUG in
  1) set -x ; VERBOSE="1"
	 ;;
  *)
     ;;
esac

# go to tmp directory
TMPDIR=/tmp/`whoami`
mkdir -p ${TMPDIR}
if [ $? -ne 0 ]
then
	error "Cannot mkdir -p ${TMPDIR}"
	exit 1
fi
cd $TMPDIR

LOCKFILE=${TMPDIR}/`basename $0 .sh`_${APPLICATION}.lock

if [ -f ${LOCKFILE} ]
then
	error "$0 already running ..."
	exit 1
fi

# BEGIN
touch ${LOCKFILE}

# calcul dates selon periode

if [ $PERIODE = "hebdo" ]
then
	if [ ! $DECAL = 0 ]
		then
		echo -e "\nDécalage de $DECAL jours !\n"
	fi
	decal_stop=${DECAL}
	date_fin=`date '+%d/%m/%Y' --date "${decal_stop} days ago"`
	decal_start=$((${DECAL}+7))
	date_debut=`date '+%d/%m/%Y' --date "${decal_start} days ago"`
elif [ $PERIODE = "mensuel" ]
then
	if [ ! $DECAL = 0 ]
		then
		echo -e "\nDécalage de $DECAL mois !\n"
	fi
	decal_stop=${DECAL}
	date_fin=`date '+01/%m/%Y' --date "${decal_stop} months ago"`
	decal_start=$((${DECAL}+1))
	date_debut=`date '+01/%m/%Y' --date "${decal_start} months ago"`
elif [ $PERIODE = "annuel" ]
then
	if [ ! $DECAL = 0 ]
		then
		echo -e "\nDécalage de $DECAL année !\n"
	fi
	decal_stop=${DECAL}
	date_fin=`date '+01/01/%Y' --date "${decal_stop} year ago"`
	decal_start=$((${DECAL}+1))
	date_debut=`date '+01/01/%Y' --date "${decal_start} year ago"`
else
	help
	error " ==> Période de rapport inconnue !"
	rm -f ${LOCKFILE}
	exit 1
fi

POSTURL="pdf_tdb?force=1&debut=${date_debut}&fin=${date_fin}"
url="empty"

if [ $TYPE = 'dg' -o $TYPE = 'all' ]
then
	reset
	url="${PREURL}/stats_dg/${POSTURL}"
	print_message $url

	query="SELECT e.email FROM travaille_pour tp, employe e, userid u \
WHERE tp.ref_fonction=6 AND tp.ref_societe=1 AND tp.ref_statut=0 AND tp.fin IS NULL AND tp.ref_personne_physique=e.uid AND u.ref_personne_physique=e.uid AND u.ref_statut=0 AND e.stats=true"
	for email in `exec_sql "$query" | dos2unix -f --`
	  do
	  can_generate=1
	  echo $email >> rapport_mails.lst
	done

	cp -f $HTTPROOTDIR/static/message.html rapport_message.html
	base_replace
	replace.sh -r '<TYPE>' -s "Direction GĂ©nĂ©rale" -f rapport_message.html

	if [  $EMAIL = 0 -a $VERBOSE = 0 ]
		then
		#echo "--> Génération silencieuse de $url"
		$WGET tmp_file.pdf $url
	elif [ $VERBOSE = 0 -a $can_generate = 1 ]
		then
		filename="rapport_DG_${PERIODE}_`date '+%d-%m-%Y' --date '1 day ago'`.pdf"
		$WGET $filename $url
		if [ -s $filename ]
			then
			subject="[Zen] Rapport ${PERIODE} ${VERSION} Direction GĂ©nĂ©rale"
			mailing -f rapport_mails.lst -l $LOGFILE -e "$MAILTO" -s "$subject" -m rapport_message.html -C "utf-8" -H $SMTPHOST -a $filename -q
		else
			print_message " --> File ${filename} is empty !"
		fi
		rm -f $filename
	elif [ $VERBOSE = 1 -a  $can_generate = 1 ]
		then
		echo "[DEBUG] email: $email"
	elif [ $VERBOSE = 1 -a $can_generate = 0 ]
		then
		echo "[WARNING] no email for Dgs !"
	fi
	if [ $VERBOSE = 1 ]
		then
		echo '.'
	fi
fi


if [ $TYPE = 'manager'  -o $TYPE = 'all' ]
then
	url="${PREURL}/stats_manager/${POSTURL}"
	exec_sql "SELECT uid, code FROM departement WHERE ref_statut=0 AND uid!=0 AND stats=true" | while read line
	  do
	  departement=`echo $line | cut -d'|' -f1`
	  code=`echo $line | cut -d'|' -f2`
	  query="SELECT e.email FROM employe e, affectation a, userid u \
WHERE a.ref_employe=e.uid AND a.ref_fonction=4 AND a.ref_statut=0 AND u.ref_personne_physique=e.uid \
AND a.fin IS NULL AND a.ref_departement = ${departement} \
AND e.ref_statut = 0 AND u.ref_statut = 0 AND e.stats = true"
	  reset
	  for email in `exec_sql "$query"`
		do
		can_generate=1
		echo "$email" >> rapport_mails.lst
	  done

	  cp -f $HTTPROOTDIR/static/message.html rapport_message.html
	  base_replace
	  replace.sh -r '<TYPE>' -s "Direction Support ${code}" -f rapport_message.html

	  print_message "${url}&ref_departement=${departement}"
	  if [  $EMAIL = 0 -a $VERBOSE = 0 ]
		  then
		  echo "--> Génération silencieuse de $url&ref_departement=${departement}"
		  $WGET tmp_file.pdf "${url}&ref_departement=${departement}"
	  elif [ $VERBOSE = 0 -a $can_generate = 1 ]
		  then
		  filename="rapport_direction_${code}_${PERIODE}_`date '+%d-%m-%Y' --date '1 day ago'`.pdf"
		  $WGET $filename "${url}&ref_departement=${departement}"
		  if [ -s $filename ]
			  then
			  subject="[Zen] Rapport ${PERIODE} ${VERSION} ${code}"
			  mailing -f rapport_mails.lst -l $LOGFILE -e "$MAILTO" -s "$subject" -m rapport_message.html -C "UTF-8" -H $SMTPHOST -a $filename -q
		  else
			  print_message " --> File ${filename} is empty !"
		  fi
		  rm -f $filename
	  elif [ $VERBOSE = 1 -a  $can_generate = 1 ]
		  then
		  echo "[DEBUG] departement:${departement} | email: $email"
	  elif [ $VERBOSE = 1 -a $can_generate = 0 ]
		  then
		  echo "[WARNING] no email for managers in departement ${departement} !"
	  fi
	if [ $VERBOSE = 1 ]
		then
		echo '.'
	fi
	done
fi


if [ $TYPE = 'commercial'  -o $TYPE = 'all' ]
then
	url="${PREURL}/stats_commercial/${POSTURL}"
	query="SELECT a.ref_employe, a.ref_departement, d.code, e.email, e.ztitle, e.stats \
FROM affectation a, departement d, employe e, userid u \
WHERE a.fin IS NULL \
AND a.ref_statut = 0 \
AND a.ref_fonction = 2 \
AND a.uid != 0 \
AND a.ref_departement = d.uid \
AND a.stats = true \
AND a.fin IS NULL \
AND d.stats= true \
AND a.ref_employe = e.uid \
AND e.ref_statut = 0 \
AND u.ref_personne_physique = e.uid \
AND u.ref_statut = 0"
	exec_sql "${query}" | while read line
	  do
	  ref_employe=`echo $line | cut -d'|' -f1`
	  ref_departement=`echo $line | cut -d'|' -f2`
	  code=`echo $line | cut -d'|' -f3`
	  email=`echo $line | cut -d'|' -f4`
	  ename="`echo $line | cut -d'|' -f5`"
	  estats="`echo $line | cut -d'|' -f6`"
	  reset

	  if [ -n "$email" -a "$estats" = "t" ]
		  then
		  can_generate=1
		  echo "${email}" >> rapport_mails.lst
	  fi

	  cp -f $HTTPROOTDIR/static/message.html rapport_message.html
	  base_replace
	  replace.sh -r '<TYPE>' -s "commercial ${ename}" -f rapport_message.html

	  print_message "${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"

	  if [  $EMAIL = 0 -a $VERBOSE = 0 ]
		  then
		  echo "--> Génération silencieuse de ${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
		  $WGET tmp_file.pdf "${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
	  elif [ $VERBOSE = 0 -a $can_generate = 1 ]
		  then
		  filename="rapport_commercial_${code}_${PERIODE}_`date '+%d-%m-%Y' --date '1 day ago'`.pdf"
		  $WGET $filename "${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
		  if [ -s $filename ]
			  then
			  subject="[Zen] Rapport ${PERIODE} ${VERSION} ${code} pour ${ename}"
			  mailing -f rapport_mails.lst -l $LOGFILE -e "$MAILTO" -s "$subject" -m rapport_message.html -C "UTF-8" -H $SMTPHOST -a $filename -q
		  else
			  print_message " --> File ${filename} is empty !"
		  fi
		  rm -f $filename
	  elif [ $VERBOSE = 1 -a  $can_generate = 1 ]
		  then
		  echo "[DEBUG] ref_employe: $ref_employe | ref_departement: $ref_departement | code: $code | email: $email | ename: $ename"
	  elif [ $VERBOSE = 1 -a $can_generate = 0 ]
		  then
		  echo "[WARNING] no email for employe (commercial) $ref_employe ($ename) !"
	  fi
	  if [ $VERBOSE = 1 ] 
		  then
		  echo "."
	  fi
	done
fi


if [ $TYPE = 'assistant'  -o $TYPE = 'all' ]
then
	url="${PREURL}/stats_assistant/${POSTURL}"
	query="SELECT a.ref_employe, a.ref_departement, d.code, e.email, e.ztitle, e.stats \
FROM affectation a, departement d, employe e, userid u \
WHERE a.fin IS NULL \
AND a.ref_statut = 0 \
AND a.ref_fonction = 3 \
AND a.uid != 0 \
AND a.ref_departement = d.uid \
AND a.stats = true \
AND a.fin IS NULL \
AND d.stats= true \
AND a.ref_employe = e.uid \
AND e.ref_statut = 0 \
AND u.ref_personne_physique = e.uid \
AND u.ref_statut = 0"
	exec_sql "${query}" | while read line
	  do
	  ref_employe=`echo $line | cut -d'|' -f1`
	  ref_departement=`echo $line | cut -d'|' -f2`
	  code=`echo $line | cut -d'|' -f3`
	  email=`echo $line | cut -d'|' -f4`
	  ename="`echo $line | cut -d'|' -f5`"
	  estats="`echo $line | cut -d'|' -f6`"
	  reset

	  if [ -n "$email" -a "$estats" = "t" ]
		  then
		  can_generate=1
		  echo "$email" >> rapport_mails.lst
	  fi

	  cp -f $HTTPROOTDIR/static/message.html rapport_message.html
	  base_replace
	  replace.sh -r '<TYPE>' -s "Assistant (${ename})" -f rapport_message.html

	  print_message "${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
	  
	  if [  $EMAIL = 0 -a $VERBOSE = 0 ]
		  then
		  echo "--> Génération silencieuse de ${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
		  $WGET tmp_file.pdf "${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
	  elif [ $VERBOSE = 0 -a $can_generate = 1 ]
		  then
		  filename="rapport_assistant_${code}_${PERIODE}_`date '+%d-%m-%Y' --date '1 day ago'`.pdf"
		  $WGET $filename "${url}&ref_departement=${ref_departement}&ref_employe=${ref_employe}"
		  if [ -s $filename ]
			  then
			  subject="[Zen] Rapport ${PERIODE} ${VERSION} ${code} pour ${ename}"
			  mailing -f rapport_mails.lst -l $LOGFILE -e "$MAILTO" -s "$subject" -m rapport_message.html -C "UTF-8" -H $SMTPHOST -a $filename -q
		  else
			  print_message " --> File ${filename} is empty !"
		  fi
		  rm -f $filename
	  elif [ $VERBOSE = 1 -a  $can_generate = 1 ]
		  then
		  echo "[DEBUG] ref_employe: $ref_employe | ref_departement: $ref_departement | code: $code | email: $email | ename: $ename"
	  elif [ $VERBOSE = 1 -a $can_generate = 0 ]
		  then
		  echo "[WARNING] no email for employe (assistant) $ref_employe ($ename) !"
	  fi
	  if [ $VERBOSE = 1 ]
		  then
		  echo '.'
	  fi
	done
fi

if [ $TYPE != 'all' -a $TYPE != 'commercial' -a $TYPE != 'manager' -a $TYPE != 'assistant' -a $TYPE != 'dg' ]
	then
	help
	error " ==> Type de rapport inconnu !"
	exit 2
fi


# END
print_message "done."
rm -f ${LOCKFILE}

