#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Daemon d'envoie des sms par rabbitmq
# License GPL2
# Gabriel Détraz, pompé sur cransticket de Daniel Stan

from __future__ import print_function
import sys,os,pwd,grp
from gammu import smsd
import common
import pika
import json
import config

daemon = smsd.SMSD('/etc/gammu-smsdrc')

def run():
	conn = pika.BlockingConnection(config.PARAMS)
	ch = conn.channel()
	ch.queue_declare(queue=config.QUEUE)
	def callback(ch, method, properties, body):
    		print (" [x] Received %r" % (body,))
                message = {
                        'Text': json.loads(body)['sms'],
                        'SMSC' : { 'Location' : 1 },
                        'Number' : json.loads(body)['numero'],
                        }
                daemon.InjectSMS([message])
	ch.basic_consume(callback, queue=config.QUEUE, no_ack=True)
	ch.start_consuming()
	conn.close()
# fork en arrière plan + pidfile

if __name__ == "__main__":
    if '-fg' in sys.argv:
        run()
        exit()
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print("fork #1 failed: %d (%s)" % (e.errno, e.strerror),file=sys.stderr)
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")   #don't prevent unmounting....
    os.setsid()
    os.umask(0)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent, print eventual PID before
            #print "Daemon PID %d" % pid
            open(common.PIDFILE, 'w').write("%d" % pid)
            sys.exit(0)
    except OSError, e:
        print("fork #2 failed: %d (%s)" % (e.errno, e.strerror),file=sys.stderr)
        sys.exit(1)

    # start the daemon main loop
    run()

