#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-
"""
Script qui alerte dès qu'une partition se monte en ro

Gabriel Détraz
Licence GPL2
"""

import subprocess

from lc_ldap import shortcuts
from gestion import secrets_new as secrets
import pika
import json

ldap = shortcuts.lc_ldap_readonly()

nounous_actif = ldap.search(u'(&(droits=nounou)(droits=cableur))',mode='rw')

list_num = [unicode(noun['tel'][0]) for noun in nounous_actif]

partoches_ro = []

QUEUE_NAME = 'SMS'

# On controle les partoches
partoches = subprocess.check_output(['mount'])

for part in partoches.split('\n'):
    if '(ro,' in part:
        print part
        partoches_ro.append(part.split()[2])

# On alerte
if partoches_ro:
    CREDS = pika.credentials.PlainCredentials('sms', secrets.get('rabbitmq_sms'), True)

    PARAMS = pika.ConnectionParameters(host='rabbitmq.crans.org',
        port=5671, credentials=CREDS, ssl=True)

    rabbit_c = pika.BlockingConnection(PARAMS)
    ch = rabbit_c.channel()

    ch.queue_declare(QUEUE_NAME)

    for num in list_num:
        SMS = {'numero': num, 'sms': 'Des partitions sont en ro sur zbee : ' + str(partoches_ro)}

        ch.basic_publish(exchange='', routing_key=QUEUE_NAME,
            body=json.dumps(SMS))
