#!/usr/bin/env python
# GPL. (C) 2014 Paolo Patruno.

# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by 
# the Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
# 

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'rmap.settings'
import django
django.setup()

from rmap import daemon
import pika, subprocess
import rmap.settings

user=rmap.settings.amqpuser
password=rmap.settings.amqppassword
host="localhost"
queue="configuration"

amqp2djangod = daemon.Daemon(
        stdin="/dev/null",
        stdout=rmap.settings.logfileamqp2djangod,
        stderr=rmap.settings.errfileamqp2djangod,
        pidfile=rmap.settings.lockfileamqp2djangod,
        user=rmap.settings.useramqp2djangod,
        group=rmap.settings.groupamqp2djangod
)

def main(self):
    import rmap.rmap_core

    rmap.rmap_core.receivejsonfromamqp(user=user,password=password,host=host,queue=queue)

if __name__ == '__main__':

    import sys, os
    amqp2djangod.cwd=os.getcwd()

    if amqp2djangod.service():

        sys.stdout.write("Daemon started with pid %d\n" % os.getpid())
        sys.stdout.write("Daemon stdout output\n")
        sys.stderr.write("Daemon stderr output\n")

        main(amqp2djangod)  # (this code was run as script)

        for proc in amqp2djangod.procs:
            proc.wait()

        sys.exit(0)
