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

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 utils.sendmail import actually_sendmail

# 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):
    if 'canonicalAlias' in adh.attrs.keys():
        mailaddrs.add(str(adh['canonicalAlias'][0]))
    elif 'mail' in adh.attrs.keys():
        mailaddrs.add(str(adh['mail'][0]))
    elif 'uid' in adh.attrs.keys():
        mailaddrs.add(str(adh['uid'][0]) + '@crans.org')
    else:
        raise ValueError("%r has nor mail nor canonicalAlias, only %s" % (adh, adh.attrs.keys()))

echecs=[]
From = 'ca@crans.org'
for To in mailaddrs:
    cprint(u"Envoi du mail à %s" % To)
    mailtxt=mail.generate('ago', {'To':To, 'From': From})
    if PREV:
        print mailtxt.as_string()
    try:
        if SEND:
            actually_sendmail('ca@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
