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

import sys,os,hashlib

import lc_ldap.shortcuts
from asterisk_reload_conf import reload_config


def gen_multidial(name, entensions):
   dial="""
exten => %(name)s,1,Ringing
exten => %(name)s,n,Wait(4)
exten => %(name)s,n,Answer
exten => %(name)s,n,Dial(%(entensions)s,30)
exten => %(name)s,n,Wait(3)
exten => %(name)s,n,VoiceMail(%(name)s@666)
exten => %(name)s,n,Hangup()
""" % {'name':name, 'entensions': '&'.join('SIP/1%04d' % num for num in entensions)}
   return dial

if __name__ == '__main__' :
    conn=lc_ldap.shortcuts.lc_ldap_admin()
    multidial=""
    for droit in ['nounou', 'bureau', 'cableur', 'imprimeur']:
        multidial+=gen_multidial(droit, (adh['aid'][0].value for adh in conn.search(u'(&(droits=%s)(!(chbre=EXT)))' % droit)))
    multidial_md5=hashlib.md5(multidial).hexdigest()
    try:
        multidial_old_md5=hashlib.md5(open('/usr/scripts/var/sip/sip_multidial','r').read()).hexdigest()
    except IOError:
        multidial_old_md5=""
    if multidial_md5 !=multidial_old_md5:
        file=open('/usr/scripts/var/sip/sip_multidial.new','w')
        file.write(multidial)
        file.close()
        os.rename('/usr/scripts/var/sip/sip_multidial.new','/usr/scripts/var/sip/sip_multidial')
        reload_config('dialplan')
