summaryrefslogtreecommitdiffstats
path: root/abs/core/LinHES-config/timezip.py
blob: c6c68d118519873e996259efb5a9c6816c7401d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# import MySQL module
#used to import the zipcode/timezone/nfs info fromMBE
import MySQLdb
import sys
import getopt
import socket
import urllib2
socket.setdefaulttimeout(10)

try:
    from json import loads as jsonparse
    nojson = False
except ImportError:
    try:
        from simplejson import loads as jsonparse
        nojson = False
    except ImportError:
        def jsonparse(js):
            if unsafe:
                return eval(js)
            raise RuntimeError("Neither the json or simplejson module is available.\nUse the --unsafe option to use python eval() as an ad-hoc json decoder")


def no_update(data):
    print "*  not updating %s, because a value is already present" %data



def usage():
    print " -h --help"
    print " -d  --installdb"
    print " -m --masterdb"
    print " -n  --hostname of current machine"

def latlong2_olsen(lat,lng):
    olsenttz = ''
    geo_url = "http://api.geonames.org/timezoneJSON?lat=%s&lng=%s&username=linhes_timezone" %(lat,lng)
    try:
        json_stream = urllib2.urlopen(geo_url,timeout=10)
        json_dict = jsonparse(json_stream.read().replace("\r\n",""))
        olsenttz = json_dict['timezoneId']
    except:
        print "error with geonames"

    return olsenttz

def geo_locate():
    print "    Trying to geo locate in timezip.py"
    gtz = ''
    gtz_region = ''
    gtz_subregion = ''
    #get long/lat from ip
    try:
        geo_url = "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt"
        json_stream = urllib2.urlopen(geo_url,timeout=10)
        json_dict = jsonparse(json_stream.read().replace("\r\n",""))['geobytes']
        latitude =  json_dict['latitude']
        longitude = json_dict['longitude']
    except:
        print "error with geobytes/geolocate"
        latitude = ''
        longitude = ''

    if latitude != '':
        try:
            olsenttz = latlong2_olsen (latitude,longitude)
            gtz = olsenttz
            gtz_region , gtz_subregion = olsenttz.split("/")
        except:
            print "error with geolocate"



    return gtz, gtz_region , gtz_subregion


def printvars():
    print "masterdb: " + masterdb
    print "installdb:" + installdb
    print "hostname: " + thishostname
    print "BEhostname:" + BEhostname
    #print "zipcode:" + zipcode
    print "timezone:" + tz
    print "timezone region:" + tz_region
    print "timezone subregion:" + tz_subregion
    print "nfsip:" + nfsip
    print "nfstoggle:" + nfstoggle
    print "nfsmount:"  + nfsmount
    print "nfsshare:"  + nfsshareall
    #print "hobbitclient:" + hobbitclient
    print "windowmanager:" + windowmanager
    print "windowmanager style:" + wmstyle
    print "Gallery Dir:" + gallerydir
    print "Music dir:" + musicdir
    print "Music template:" + filenametemplate
    print "-----------------------------------"
    print "\n\n\n"


# connect
def selectvars():

    global BEhostname
    global zipcode
    global tz
    global tz_region
    global tz_subregion
    global nfsip
    global nfstoggle
    global nfsmount
    global nfsshareall
    #global hobbitclient
    global windowmanager
    global wmstyle
    global musicdir
    global gallerydir
    global filenametemplate

    db = MySQLdb.connect(host=masterdb, user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
    # execute SQL statement

    try:
        cursor.execute("select hostname from settings where value='BackendServerIP' and data=(%s)",(masterdb))
        result = cursor.fetchone()
        BEhostname=result[0]
    except TypeError:
        BEhostname=""

    try:
        cursor.execute("select data from settings where value='HostCentralNFSIP' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        nfsip=result[0]
    except TypeError:
        nfsip=""

    try:
        cursor.execute("select data from settings where value='HostHaveCentralNFS' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        nfstoggle=result[0]
    except TypeError:
        nfstoggle="no"


    try:
        cursor.execute("select data from settings where value='HostNFSmountpoint' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        nfsmount=result[0]
    except TypeError:
        nfsmount=""

    try:
        cursor.execute("select data from settings where value='HostCentralNFSallhosts' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        nfsshareall=result[0]
    except TypeError:
        nfsshareall="0"



    try:
        #cursor.execute("select data from settings where value='HostTimeZonetemp' and hostname=(%s)",(BEhostname))
        cursor.execute("select data from settings where value='HostTimeZone' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        tz=result[0]
    except TypeError:
        tz = ""

    if tz == "":
        tz,tz_region, tz_subregion = geo_locate()
    else:
        try:
            cursor.execute("select data from settings where value='HostTimeZoneRegion' and hostname=(%s)",(BEhostname))
            result = cursor.fetchone()
            tz_region=result[0]
        except TypeError:
            tz_region=""

        tempsubregion="HostTimeZoneRegion_" + tz_region
        try:
            cursor.execute("select data from settings where value=%s and hostname=(%s)",(tempsubregion,BEhostname))
            result = cursor.fetchone()
            tz_subregion=result[0]
        except TypeError:
            tz_subregion=""


###############
    #if  ( thishostname != BEhostname ):
        #cursor.execute("select data from settings where value='GlobalServiceHobbitserver'")
        #result = cursor.fetchone()
        #try:
            #hobbitclient=result[0]
        #except:
            #hobbitclient="1"
    #else:
            #hobbitclient="1"



    try:
        cursor.execute("select data from settings where value='HostWindowManager' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        windowmanager=result[0]
    except TypeError:
        windowmanager=""


    try:
        cursor.execute("select data from settings where value='HostEnhancedWMStyle' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        wmstyle=result[0]
    except TypeError:
        wmstyle=""


    try:
        cursor.execute("select data from settings where value='MusicLocation' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        musicdir=result[0]
    except TypeError:
        musicdir=""


    try:
        cursor.execute("select data from settings where value='FilenameTemplate' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        filenametemplate=result[0]
    except TypeError:
        filenametemplate=""


    try:
        cursor.execute("select data from settings where value='GalleryDir' and hostname=(%s)",(BEhostname))
        result = cursor.fetchone()
        gallerydir=result[0]
    except TypeError:
        gallerydir=""


def insertvars():

    db = MySQLdb.connect(host=installdb, user="mythtv", passwd="mythtv", db="mythconverg")
    cursor = db.cursor()
##inserting the zipcode
    #cursor.execute("select * from settings where value='HostZipcode' and hostname=(%s)",(thishostname))
    #result = cursor.fetchone()
    #if ( zipcode!="" ):
        #if (result == None):
            #cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostZipcode',(%s),(%s))",(zipcode,thishostname))
            #print "inserting zipcode"
        #else:
            #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostZipcode'",(zipcode,thishostname))
            #print "updating zipcode"

#inserting the timezone

    if ( tz != ""):
        cursor.execute("select *  from settings where value='HostTimeZone' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostTimeZone',(%s),(%s))",(tz,thishostname))
            print "inserting timezone"
        else:
            cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostTimeZone'",(tz,thishostname))
            print "updating timezone"

        cursor.execute("select *  from settings where value='HostTimeZoneRegion' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostTimeZoneRegion',(%s),(%s))",(tz_region,thishostname))
            print "inserting timezone region"
        else:
            cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostTimeZoneRegion'",(tz_region,thishostname))
            print "updating timezone region"

        tempsubregion="HostTimeZoneRegion_" + tz_region

        cursor.execute("select *  from settings where value=%s and hostname=(%s)",(tempsubregion,thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ((%s),(%s),(%s))",(tempsubregion,tz_subregion,thishostname))
            print "inserting timezone subregion"
        else:
            cursor.execute("update settings set data=(%s) where hostname=(%s) and value=(%s)",(tz_subregion,thishostname,tempsubregion))
            print "updating timezone subregion"


##start of NFSIP
    if nfstoggle == "yes" :
        print "BE has a central storage"
        #if nfsshareall == "0":
            #print "BE is not sharing central, starting config"
        if ( nfsip != ""):
            cursor.execute("select data from settings where value='HostCentralNFSIP' and hostname=(%s)",(thishostname))
            result = cursor.fetchone()
            if (result == None):
                cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostCentralNFSIP',(%s),(%s))",(nfsip,thishostname))
                print "inserting nfsip"
            else:
                no_update("HostCentralNFSIP")
                #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostCentralNFSIP'",(nfsip,thishostname))
                #print "updating nfsip"
        if ( nfsmount !="") :
            cursor.execute("select data from settings where value='HostNFSmountpoint' and hostname=(%s)",(thishostname))
            result = cursor.fetchone()
            if (result == None):
                cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostNFSmountpoint',(%s),(%s))",(nfsmount,thishostname))
                print "inserting nfsmountpoint"
            else:
                no_update("nfsmount")
                #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostNFSmountpoint'",(nfsmount,thishostname))
                #print "updating nfsmount"
        #else:
            #print "BE is sharing, config sync skipped"
    else:
        print "BE has no central storage"

    #windowmanager
    if windowmanager != "":
        cursor.execute("select *  from settings where value='HostWindowManager' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostWindowManager',(%s),(%s))",(windowmanager,thishostname))
            print "inserting windowmanager"
        else:
            no_update("windowmanager")
            #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostWindowManager'",(windowmanager,thishostname))
            #print "updating windowmanager"


    if wmstyle != "" :
        cursor.execute("select *  from settings where value='HostEnhancedWMStyle' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('HostEnhancedWMStyle',(%s),(%s))",(wmstyle,thishostname))
            print "inserting windowmanager style"
        else:
            no_update("wm_style")
            #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='HostEnhancedWMStyle'",(wmstyle,thishostname))
            #print "updating windowmanager style"

#music and gallery

    if ( musicdir != "" ):
        cursor.execute("select * from settings where value='MusicLocation' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('MusicLocation',(%s),(%s))",(musicdir,thishostname))
            print "inserting musicdir"
        else:
            no_update("musicdir")
            #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='MusicLocation'",(musicdir,thishostname))
            #print "updating musicdir"

    if ( filenametemplate != "" ):
        cursor.execute("select * from settings where value='FilenameTemplate' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('FilenameTemplate',(%s),(%s))",(filenametemplate,thishostname))
            print "inserting filenametemplate"
        else:
            no_update("filenametemplate")
            #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='FilenameTemplate'",(filenametemplate,thishostname))
            #print "updating filenametemplate"

    if ( gallerydir != "" ):
        cursor.execute("select * from settings where value='GalleryDir' and hostname=(%s)",(thishostname))
        result = cursor.fetchone()
        if (result == None):
            cursor.execute("INSERT INTO  settings (value,data,hostname) VALUES ('GalleryDir',(%s),(%s))",(gallerydir,thishostname))
            print "inserting gallerydir"
        else:
            no_update("gallerydir")
            #cursor.execute("update settings set data=(%s) where hostname=(%s) and value='GalleryDir'",(gallerydir,thishostname))
            #print "updating gallerydir"




def main(argv):
    global masterdb
    global installdb
    global thishostname
    thishostname=""
    global BEhostname
    global zipcode
    global tz
    global tz_region
    global tz_subregion
    #global nfsip
    #global hobbitclient
    global musicdir
    global gallerydir
    global filenametemplate

    try:
        opts, args = getopt.getopt(argv, "hm:d:n:", ["help", "masterdb=", "installdb=" , "hostname=" ] )
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
             usage()
             sys.exit()
        elif opt in ( "-d" , "--installdb"):
             installdb = arg
        elif opt in ("-m", "--masterdb"):
             masterdb = arg
        elif opt in ("-n", "--hostname"):
             thishostname = arg

    if ( thishostname == "" ):
         thishostname = socket.gethostname()

    selectvars()
    printvars()
    insertvars()
if __name__ == "__main__":
    main(sys.argv[1:])