#!/bin/bash
# Validation_don
# Copyright 2022 Adrien Bourmault
# Licence AGPL v3

set -e

#$1 = numero de don
nom=$2
statut=$3
adresse=$4
montant_declare=$5
courriel=$6

PASSWORD=$(cat ~/.secret/gestion_api_password)

##############################################################################

# RECUPERATION DONNEES
requete=$(curl https://api666:$PASSWORD@gestion.a-lec.org/api/sql/ -s -d "SELECT * FROM acc_transactions tr INNER JOIN acc_transactions_lines l ON tr.id = l.id_transaction WHERE tr.notes = $1 and id_account = 469")

requete=$(echo -e $requete | tr -d "{}\"[] " | cut -c 10-1000)

if [ -z "$requete" ]
then
	echo "  DON NON REGLE !"
	exit 2
fi

IFS="," read -a results <<< $requete

notes=$(echo ${results[4]} | cut -d ":" -f 2)
reference=$(echo ${results[5]} | cut -d ":" -f 2)
date=$(echo ${results[6]} | cut -d ":" -f 2)
montant=$(echo ${results[15]} | cut -d ":" -f 2)
montant=${montant::-2},${montant: -2:2}

# GENERATION

if [ "$reference" = "null" ]
then
	echo "  PAIEMENT INVALIDE !"
	exit 2
fi

forme="Déclaration de don manuel"
nature="Numéraire"
siren="null"

echo "Nom ou dénomination: $nom"
echo "SIREN: $siren"
echo "Statut: $statut"
echo "Adresse: $adresse"
echo "Somme: $montant €" #OK
echo "Date de versement: $date" #OK
echo "Forme: $forme" #OK
echo "Nature: $nature" #OK
echo "Mode de versement: $reference" #OK
echo "Numéro du don lié: $notes" #OK

if [ "$siren" = "null" ]
then
	./generer_don.sh "$nom" "$statut" "$adresse" "$montant" "$date" "$forme" "$nature" "$reference" > /dev/null
else
	./generer_don.sh "$nom (SIREN $siren)" "$statut" "$adresse" "$montant" "$date" "$forme" "$nature" "$reference" > /dev/null
fi

FILE=$(echo "$nom" | tr " " "_")_reçu_don_$(echo "$date" | tr "/" ".").pdf
DATE_VERSEMENT=$(date -d"$date" +%d/%m/%Y)

# ENVOI
(cat mail_don.txt | sed "s|DATE-DON|$(echo "$date" | tr "/" "-")|g" | sed "s/COURRIEL-DON/$courriel/g" ; base64 "$FILE"; echo "--------------3yxkFgv0AINs5nd0i6BJrWaV--") | /usr/sbin/sendmail -i -- "$courriel" tresorier@a-lec.org > /dev/null

mv $FILE /srv/validation_don.d

exit 0