#!/usr/bin/env python

# Copyright (c) 2015 Paolo Patruno <p.patruno@iperbole.bologna.it>
#                    Emanuele Di Giacomo <edigiacomo@arpa.emr.it>

# 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 django.conf import settings
from django.core.exceptions import ObjectDoesNotExist

import rmap.settings
from rmap import daemon
from rmap import __version__
from rmap.stations.models import StationMetadata
try:
  from rmap import sensordriver
except RuntimeError,e:
  print "ERROR:", str(e)

logfilermap=rmap.settings.logfilestationd
errfilermap=rmap.settings.errfilestationd
lockfilermap=rmap.settings.lockfilestationd
userrmap=rmap.settings.userstationd
grouprmap=rmap.settings.groupstationd

stationd = daemon.Daemon(
        stdin="/dev/null",
        stdout=logfilermap,
        stderr=errfilermap,
        pidfile=lockfilermap,
        user=userrmap,
        group=grouprmap
)


def main ():

  #disable unwanted initialization and error management of kivy
  os.environ['KIVY_DOC_INCLUDE'] = "1"
  # this import overwrite stdin, stdout ... so to make daemon module work it ave to go here
  from rmap import rmapstation
  from rmap.rmapstation import station
  from signal import signal, SIGINT

  mystation=station(slug=rmap.settings.stationslug,username=rmap.settings.ident,boardslug=rmap.settings.boardslug,trip=False)
  print "background restored queue:",mystation.anavarlist,mystation.datavarlist
  mystation.display()

  signal(SIGINT, mystation.exit)

  try:
    mystation.boot(configurestation=False)
    mystation.loopforever()
  except:
    print "error on boot/loopforever"

    try:
      mystation.on_stop()
    except:
      print "error on_stop"

if __name__ == '__main__':

  import os,sys

  # this is a triky for ubuntu and debian that remove /var/run every boot
  # ATTENTION, this should be a security problem
  path=os.path.dirname(lockfilermap)
  if (not os.path.lexists(path) and path == "/var/run/rmap" ):
    os.mkdir(path)
    if (os.getuid() == 0):
      user=userrmap
      group=grouprmap
      if user is not None and group is not None:
        from pwd import getpwnam
        from grp import getgrnam
        uid = getpwnam<(user)[2]
        gid = getgrnam(group)[2]
        os.chown(path,uid,gid)

  if stationd.service(noptions=1000):

    sys.stdout.write("Stationd version "+__version__+"\n")
    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()   # (this code was run as script)

    sys.stdout.write("Daemon stopped\n")

    sys.exit(0)
