#!/bin/bash

usage() {
	echo "get_facture_free.sh : Récupère une facture Free, la convertit en postscript"
	echo "et affiche ses informations."
	echo "usage : get_facture_free [ -h for help ] -m YYYYMM -l login -p passwd"
	echo 
	echo "exemple :"
	echo "get_facture_free -m 200608 -l 0143560500 -p kjdksj"

}

while true
do
  case $1 in
	-d) debug=1
		set -x
		shift 1
		;;
	-h) usage
		exit 0
		;;
	-m) mois=$2
		shift 2
		;;
	-l) login=$2
		shift 2
		;;
	-p) pass=$2
		shift 2
		;;
	 *)
		break
		;;
  esac
done

if [ -z "$mois" ] ;	then
	usage
	exit 1
fi

outfile="/tmp/get_facture_"$$
agent='Mozilla/4.0'

curl -s -A ${agent} "http://subscribe.free.fr/login/login.pl?login=${login}&pass=${pass}&link=" --location-trusted -D ${outfile} -o /dev/null 2>/dev/null
session=`grep Location ${outfile}|grep "idt="|cut -d'?' -f 2`

 
curl -s -A ${agent} "http://adsl.free.fr/conso/liste-factures.pl?${session}" --location-trusted -o ${outfile}


no_facture=`sed 's/<\/td>/<\td>\n/g' $outfile|grep ${mois} | grep no_facture | tail -1 | sed "s/.*mois=${mois}&no_facture=\([0-9]*\).*/\1/g"`

url="https://adsl.free.fr/facture.pl?mois=${mois}&no_facture=${no_facture}&${session}"
curl -s -A ${agent} ${url} --location-trusted -o ${outfile}

no_facture=`grep FACTURE ${outfile}|sed "s/.*FACTURE: \([0-9\-]*\).*/\1/g"`
total_ht=`grep -C1 HT ${outfile} |tail -1| sed "s/.*4\">\([0-9\.]*\).*/\1/g"`
total_ttc=`grep -C1 "uro TTC]" ${outfile} |tail -1| sed "s/.*4\">\([0-9\.]*\).*/\1/g"`
ligne=`grep Ligne ${outfile}|sed "s/.*Ligne: \([0-9\.]*\).*/\1/g"`
ps_file=/tmp/facture_free_${ligne}.ps


# htmldoc --no-numbered -t ps --continuous --size a4 --left -2cm --right 2cm --fontsize 8	\
# 	-f ${outfile}.ps ${outfile} 2>/dev/null

# # C'est pas encore ça pour la transformation postscript (pas assez de marge)
# ps2ps -sPAPERSIZE=a4 ${outfile}.ps ${outfile}2.ps 2>/dev/null 
# psresize -pa4 -Pletter ${outfile}2.ps ${ps_file} 2>/dev/null

echo "ligne "${ligne}
echo "mois "${mois}
echo "no_facture "${no_facture}
echo "total_ht "${total_ht}
echo "total_ttc "${total_ttc}
echo "html_file "${outfile}

