#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-

import os
import sys
import smtplib
from gestion import config
from gestion.affich_tools import cprint
from gestion import mail
import time
import lc_ldap.shortcuts
import lc_ldap.crans_utils as crans_utils
from email.header import Header
from email.mime.application import MIMEApplication
from utils.sendmail import actually_sendmail

STATUTS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "template/age/statuts.pdf")
RI_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "template/age/reglement.pdf")

# Attention, si à True envoie effectivement les mails
SEND=('--do-it' in sys.argv)
# Prévisualisation
PREV=('--prev' in sys.argv)

ldap_filter=u"(&(finAdhesion>=%(date)s)(aid=*))" % {'date': crans_utils.to_generalized_time_format(time.time())}
#ldap_filter=u"(|(uid=dstan)(uid=lasseri))"

conn=lc_ldap.shortcuts.lc_ldap_readonly()
mailaddrs=set()
for adh in conn.search(ldap_filter, sizelimit=2000):
    _mail = adh.get_mail()
    if _mail is None:
        print "%r has no valid contact email." % (adh,)
        continue
    mailaddrs.add(str(_mail))

echecs=[]
From = 'ca@crans.org'
for To in mailaddrs:
    cprint(u"Envoi du mail à %s" % To)
    mailtxt = mail.generate('age', {'To':To, 'From': From, 'lang_info': 'English version below',})
    mailtxt["Reply-To"] = Header("ca@crans.org")

#    fichier = open(STATUTS_PATH, 'rb')
#    part = MIMEApplication(fichier.read(), 'pdf')
#    part.add_header('Content-Disposition', 'attachment', filename="statuts.pdf")
#    mailtxt.attach(part)
#    fichier = open(RI_PATH, 'rb')
#    part = MIMEApplication(fichier.read(), 'pdf')
#    part.add_header('Content-Disposition', 'attachment', filename="reglement.pdf")
#    mailtxt.attach(part)

    if PREV:
        print mailtxt.as_string()
    try:
        if SEND:
            actually_sendmail('bureau@crans.org', (To,), mailtxt)
            cprint(" Envoyé !")
        else:
            cprint(" (simulé)")
    except:
        cprint(u"Erreur lors de l'envoi à %s " % To, "rouge")
        echecs.append(To)

if echecs:
    print "\nIl y a eu des erreurs :"
    print echecs
