#!/usr/bin/python

########################################
##   snuggle daemon - CellID logging  ##
########################################
# get cellid codes via dbus command
#     MCC   :   Mobile Country Code;
#     MNC   :   Mobile Network Code;
#     LAC   :   Local Area Code;
#     CellID:   Cellid;
########################################


# Copyright (c) 2011 Christos Zamantzas
# Licenced under GPLv2

#Author: Christos Zamantzas <christos.zamantzas@gmail.com>
Version = '2.8-0'

# standard modules
import os
import sys
import time

# DBus modules
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject ## might give segmentation fault; issue: https://bugs.maemo.org/show_bug.cgi?id=10752

# Constants 
country         = "en"
device          = "Nokia-N900-M5"
user_agent      = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
url_mmap        = 'http://www.google.com/glm/mmap'
url_geo         = 'http://maps.google.com/maps/geo'
url_map         = 'http://maps.google.com/maps'

# dbus variables

dbus_cellid     = 'dbus-send --system --print-reply=literal\
                            --type=method_call\
                            --dest=com.nokia.phone.net\
                            /com/nokia/phone/net Phone.Net.get_registration_status'

# application paths and names                             
LogPath         = '/home/user/.config/snuggle'
LogCellInfo     = 'cellInfo.csv'

###########################################################################################

def ExitDaemon():
    '''Exit snuggleDaemon'''

    print 'snuggleDaemon has stopped'
    sys.exit(1)
    
def GetTime():
    '''Convert time to readable format.'''

    t = time.localtime( time.time() )

    if t[2] <= 9:
        t2 = '0' + str(t[2])
    else:
        t2 = t[2]

    if t[1] <= 9:
        t1 = '0' + str(t[1])
    else:
        t1 = t[1]

    if t[0] <= 9:
        t0 = '0' + str(t[0])
    else:
        t0 = t[0]

    if t[3] <= 9:
        t3 = '0' + str(t[3])
    else:
        t3 = t[3]

    if t[4] <= 9:
        t4 = '0' + str(t[4])
    else:
        t4 = t[4]

    if t[5] <= 9:
        t5 = '0' + str(t[5])
    else:
        t5 = t[5]
    
    return "%s-%s-%sT%s:%s:%sZ" % (t0, t1, t2, t3, t4, t5)

def checkFile(Path, File):       
    ''' Check if a file exists. '''

    try:
        f = open(Path + '/' + File, 'r')
        f.close()
    except:
        return False
    else:
        return True

def doTrackOn():   

    try:            
       DBusGMainLoop(set_as_default = True)

       ReceiverSet()
       gobject.MainLoop().run()

    except Exception, e:
       print 'Snuggle FATAL ERROR:\n%s' % e

def doTrackOff():   
   
    ReceiverUnSet()
    time.sleep(1)
    gobject.MainLoop().quit()
                 
def ReceiverSet():
    '''Setup the change of cell info signal receiver'''
    bus = dbus.SystemBus()
    # bus.add_signal_receiver(doGetCellID, 
    bus.add_signal_receiver(received_cellid_info, 
                            path           = '/com/nokia/phone/net',
                            dbus_interface = 'Phone.Net',
                            signal_name    = 'registration_status_change')
    print bus  

def ReceiverUnSet():
    '''Unset the change of cell info signal receiver'''
    bus = dbus.SystemBus()
    # bus.remove_signal_receiver(doGetCellID, 
    bus.remove_signal_receiver(received_cellid_info, 
                            path           = '/com/nokia/phone/net',
                            dbus_interface = 'Phone.Net',
                            signal_name    = 'registration_status_change')
    print bus  

def get_cellid_info():
    '''Get cellid info from system'''
      
    info = os.popen(dbus_cellid).read().replace('   byte ','').replace('   uint32 ','').replace('   uint16 ','').replace('   int32 ','').split('\n')
    LAC    = int(info[1])
    CELLID = int(info[2])
    MNC    = int(info[3])
    MCC    = int(info[4])

    os.system( 'echo \"%s,%s,%s,%s,%s\" >> %s/%s'% ( GetTime(), MCC, MNC, LAC, CELLID, LogPath, LogCellInfo )) 
    return MCC, MNC, LAC, CELLID

def received_cellid_info(other1, LAC, CELLID, MNC, MCC, other2, other3):
    '''Decode cellid info from signal'''
      
    MCC    = int(MCC)
    MNC    = int(MNC)
    LAC    = int(LAC)
    CELLID = int(CELLID)
    other1 = int(other1)
    other2 = int(other2)
    other3 = int(other3)
    print 'Received cell info:'
    print 'MCC:', MCC, ', MNC:', MNC, ', LAC: ', LAC, ', CellID:', CELLID, ',other: ', other1, other2, other3
 
    os.system( 'echo \"%s,%s,%s,%s,%s\" >> %s/%s'% ( GetTime(), MCC, MNC, LAC, CELLID, LogPath, LogCellInfo )) 
      
try:    

    ##Check if temp folder is available
    if os.path.exists(LogPath) == False:
       os.system('mkdir %s' % LogPath)
    else:
       pass
       
    ##Check if log files exist, if not create them
    if checkFile(LogPath, LogCellInfo) == False:
       os.system ( 'echo \"Timestamp,MCC,MNC,LAC,CELLID\" > %s/%s' % (LogPath, LogCellInfo) )
    else:
       pass
         
    ##Get info on first time
    get_cellid_info()
    doTrackOn()
    
except Exception, e:
    print '<<< Snuggle Daemon FATAL ERROR:\n%s >>>' % e
    doTrackOff()
    ExitDaemon()
