Browse Source

lazy update

John ShaggyTwoDope Jenkins 4 years ago
parent
commit
da0d197947
3 changed files with 353 additions and 4 deletions
  1. 7
    3
      backup
  2. 346
    0
      inotify-daemon
  3. 0
    1
      sortfiles

+ 7
- 3
backup View File

@@ -19,7 +19,7 @@ INCLUDE10="/home/shaggy/.cliweather /home/shaggy/.conkyrc /home/shaggy/.gitconfi
19 19
 INCLUDE11="/home/shaggy/.msmtprc /home/shaggy/.nanorc /home/shaggy/.netrc /home/shaggy/.offlineimaprc"
20 20
 INCLUDE12="/home/shaggy/.notmuch-config /home/shaggy/.Xdefaults /home/shaggy/.xinitrc /home/shaggy/.xprofile"
21 21
 INCLUDE13="/home/shaggy/.zshrc /home/shaggy/.zsh_history /home/shaggy/.screenrc"
22
-INCLUDE14="/home/shaggy/scripts /home/shaggy/private"
22
+INCLUDE14="/home/shaggy/scripts /home/shaggy/private /home/shaggy/.gnupg"
23 23
 
24 24
 BACKUPDIRARCH=/riddlebox/Dropbox/backups/archconfigs/
25 25
  
@@ -29,6 +29,7 @@ BACKUPDIRARCH=/riddlebox/Dropbox/backups/archconfigs/
29 29
 
30 30
 # Target file
31 31
 TARTARGET="/riddlebox/Dropbox/backups/backup-$DATE.tar.gz"
32
+ETCTARTARGET="/riddlebox/Dropbox/backups/ETC.tar.gz"
32 33
 
33 34
 TARTARGETMAIL="/riddlebox/Dropbox/backups/backupmail-$DATE.tar.gz"
34 35
 
@@ -37,7 +38,10 @@ TARTARGETMAIL="/riddlebox/Dropbox/backups/backupmail-$DATE.tar.gz"
37 38
 tar -czvf $TARTARGETMAIL /home/shaggy/Maildir
38 39
 
39 40
 tar -czvf $TARTARGET /home/shaggy/bin $INCLUDE1 $INCLUDE2 $INCLUDE3 $INCLUDE4 $INCLUDE5 $INCLUDE6 $INCLUDE7 $INCLUDE8 $INCLUDE9 $INCLUDE10 $INCLUDE11 $INCLUDE12 $INCLUDE13 $INCLUDE14 
40
-            
41
-nice -n 19 rsync --archive --force --delete --progress --compress /etc $BACKUPDIRARCH
41
+
42
+
43
+tar -czvf $ETCTARTARGET /etc
44
+
45
+#nice -n 19 rsync --archive --force --delete --progress --compress /etc $BACKUPDIRARCH
42 46
 
43 47
 

+ 346
- 0
inotify-daemon View File

@@ -0,0 +1,346 @@
1
+#! /usr/bin/env python
2
+# -*- coding: utf-8 -*-
3
+###
4
+# Copyright (c) 2009-2010 by Elián Hanisch <lambdae2@gmail.com>
5
+#
6
+# This program is free software; you can redistribute it and/or modify
7
+# it under the terms of the GNU General Public License as published by
8
+# the Free Software Foundation; either version 3 of the License, or
9
+# (at your option) any later version.
10
+#
11
+# This program is distributed in the hope that it will be useful,
12
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+# GNU General Public License for more details.
15
+#
16
+# You should have received a copy of the GNU General Public License
17
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
+###
19
+
20
+"""\
21
+inotify-daemon [arguments ...]
22
+
23
+Notification daemon that supports libnotify or dbus.
24
+Download latest stable from:
25
+http://github.com/m4v/inotify-daemon/raw/stable/inotify-daemon
26
+
27
+This is intended to be used with WeeChat's inotify script, but any
28
+xmlrpc capable client can use it.
29
+
30
+It is recommended to use your desktop autorun settings for initialise
31
+the daemon on login, this saves you the problem of losing dbus with
32
+each login. Still you can use inotify-daemon as a detached process
33
+with screen, dtach or on boot with crontab, the daemon should be able
34
+to find a suitable dbus session if available.  inotify-daemon *must*
35
+be always run with your user's privileges, otherwise it will fail to
36
+get a dbus session if it loses it.
37
+
38
+Autostart examples:
39
+ - In KDE make a symlink in $HOME/.kde/Autostart to inotify-daemon.
40
+ - With crontab, add the following line: @reboot <path to
41
+   inotify-daemon> --host <address> --port <port>
42
+
43
+Notify methods:
44
+ - libnotify: Use libnotify for notifications, needs python-notify
45
+   installed. This is the default method.
46
+
47
+ - dbus: Uses dbus directly for notifications, this is KDE4 specific,
48
+   might not work in other desktops. Needs python-dbus.\
49
+"""
50
+
51
+__version__   = '0.2'
52
+__author__    = 'Elián Hanisch <lambdae2@gmail.com>'
53
+__copyright__ = 'Copyright (c) 2009-2010 by Elián Hanisch <lambdae2@gmail.com>'
54
+
55
+import xmlrpclib, socket, os, sys, subprocess, optparse
56
+from SimpleXMLRPCServer import SimpleXMLRPCServer
57
+
58
+global host, port, server
59
+
60
+class NotifyError(Exception):
61
+    pass
62
+
63
+class Daemon(SimpleXMLRPCServer):
64
+    stopped = False
65
+    shutdown = False
66
+    def __init__(self, addr, passwd=''):
67
+        SimpleXMLRPCServer.__init__(self, addr)
68
+        self.passwd = passwd
69
+        self.register_function(self.quit)
70
+        self.register_function(self.restart)
71
+        self.register_function(lambda : __version__, 'version')
72
+
73
+    def serve_forever(self):
74
+        while not self.stopped:
75
+            self.handle_request()
76
+            if self.shutdown:
77
+                self._restart_daemon()
78
+
79
+    def quit(self, passwd=''):
80
+        """Allows to kill the server remotely."""
81
+        if self.passwd and passwd != self.passwd:
82
+            return 'Invalid password.'
83
+        print >>sys.stderr, 'Stopping server.'
84
+        self.server_close()
85
+        self.stopped = True
86
+        return 'OK'
87
+
88
+    def restart(self, passwd=''):
89
+        """Allows to restart the server remotely."""
90
+        if self.passwd and passwd != self.passwd:
91
+            return 'Invalid password.'
92
+        print >>sys.stderr, 'Restarting server.'
93
+        self.force_restart()
94
+        return 'OK'
95
+
96
+    def force_restart(self):
97
+        self.shutdown = True
98
+
99
+    def _restart_daemon(self):
100
+        self.server_close()
101
+        self.stopped = True
102
+        # spawn a new daemon and exit
103
+        subprocess.Popen(' '.join(sys.argv), shell=True)
104
+        sys.exit(0)
105
+
106
+
107
+dbus_env = 'DBUS_SESSION_BUS_ADDRESS'
108
+class Notifications(object):
109
+    def __init__(self, method, passwd=''):
110
+        self.method = method
111
+        self.passwd = passwd
112
+
113
+    def _dispatch(self, method, args):
114
+        passwd = args[0]
115
+        if self.passwd and passwd != self.passwd:
116
+            return 'Invalid password.'
117
+        if method in ('any', 'notify'):
118
+            method = self.method
119
+        if not hasattr(self, method):
120
+            return 'Invalid notification method.'
121
+        args = args[1:]
122
+        return getattr(self, method)(*args)
123
+
124
+    def _timeout(self, s=None):
125
+        if s is not None:
126
+            t = len(s) * 150
127
+            if t < 5000:
128
+                return 5000
129
+            elif t > 60000:
130
+                return 60000
131
+        else:
132
+            t = 10000
133
+        return t
134
+
135
+    def _getDBUSSession(self):
136
+        print >>sys.stderr, 'Lost dbus daemon, trying to find a new one... '
137
+        if self.method == 'dbus':
138
+            testMethod = lambda address : testDBUS(test_dbus, address)
139
+        elif self.method == 'libnotify':
140
+            testMethod = lambda address : testDBUS(test_libnotify, address)
141
+        else:
142
+            raise NotifyError, 'No suitable method for test dbus found.'
143
+
144
+        return getDBUS(testMethod)
145
+
146
+    def _updateDBUS(self, address):
147
+        os.environ[dbus_env] = address
148
+        global server
149
+        print >>sys.stderr, 'Updated dbus address, restarting daemon...'
150
+        server.force_restart()
151
+        return 'warning:Lost dbus, notification daemon is being restarted with new address.'
152
+
153
+    def dbus(self, text, channel=None):
154
+        global host
155
+        try:
156
+            import dbus
157
+        except:
158
+            return 'Failed to import dbus, is the module installed in %s?' %host
159
+
160
+        try:
161
+            bus = dbus.SessionBus()
162
+            notify_object = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
163
+            notify = dbus.Interface(notify_object, 'org.freedesktop.Notifications')
164
+            notify.Notify('', 0, '', channel or 'notification', text, '', {}, self._timeout(text))
165
+            return 'OK'
166
+        except:
167
+            try:
168
+                address = self._getDBUSSession()
169
+            except NotifyError, e:
170
+                print >>sys.stderr, str(e)
171
+                return 'Failed to connect with the dbus daemon in %s.' %host
172
+            return self._updateDBUS(address)
173
+
174
+    def libnotify(self, text, channel=None):
175
+        global host
176
+        try:
177
+            import pynotify
178
+        except:
179
+            return 'Failed to import pynotify, is the module installed in %s?' %host
180
+
181
+        try:
182
+            if pynotify.init('WeeChat notification'):
183
+                notify = pynotify.Notification(channel or 'notification', text)
184
+                notify.set_timeout(self._timeout(text))
185
+                notify.show()
186
+                return 'OK'
187
+            else:
188
+                raise Exception
189
+        except:
190
+            try:
191
+                address = self._getDBUSSession()
192
+            except NotifyError, e:
193
+                print >>sys.stderr, str(e)
194
+                return 'Failed to connect with the dbus daemon in %s.' %host
195
+            return self._updateDBUS(address)
196
+
197
+# cmd used for test dbus session with dbus module
198
+test_dbus = """
199
+python -c '
200
+import dbus, sys
201
+try:
202
+    dbus.SessionBus()
203
+except:
204
+    sys.exit(0)
205
+else:
206
+    sys.exit(1)'
207
+"""
208
+
209
+# cmd used for test dbus session with pynotify module
210
+test_libnotify = """
211
+python -c '
212
+import pynotify, sys
213
+if pynotify.init("test"):
214
+    sys.exit(1)
215
+else:
216
+    sys.exit(0)' 2> /dev/null
217
+"""
218
+
219
+def testDBUS(cmd, address):
220
+    os.environ[dbus_env] = address
221
+    return subprocess.call(cmd, shell=True)
222
+
223
+def getDBUS(testMethod):
224
+    """
225
+    There might be times where the dbus daemon is restarted and its address changes, making
226
+    notifications impossible. Here we'll try for fetch another from our user processes. This isn't
227
+    nice but I couldn't find other way, dbus actually doesn't have a nice method for get a session
228
+    address from outside the session."""
229
+    
230
+    process_list = [ s for s in os.listdir('/proc') if s.isdigit() ]
231
+    our_uid = os.getuid()
232
+    dbus_invalid_address = set()
233
+    dbus_address = None
234
+    for process in process_list:
235
+        environ = os.path.join('/proc', process, 'environ')
236
+        if os.stat(environ).st_uid == our_uid:
237
+            fd = open(environ)
238
+            for line in fd.read().split('\x00'):
239
+                if line.startswith(dbus_env):
240
+                    dbus_address = line[len(dbus_env)+1:]
241
+                    if dbus_address not in dbus_invalid_address:
242
+                        print >>sys.stderr, 'Testing with %s ... ' %dbus_address,
243
+                        if testMethod(dbus_address):
244
+                            print >>sys.stderr, 'OK'
245
+                            return dbus_address
246
+                        else:
247
+                            print >>sys.stderr, 'Failed'
248
+                            dbus_invalid_address.add(dbus_address)
249
+                    break
250
+    raise NotifyError, 'No dbus address found.'
251
+
252
+
253
+def main(host='localhost', port=7766, method=None, passwd=''):
254
+    """
255
+    Main daemon loop."""
256
+    global server
257
+
258
+    try:
259
+        server = Daemon((host, port), passwd=passwd)
260
+    except socket.error, e:
261
+        # another server is running? lets try to kill it
262
+        try:
263
+            daemon = xmlrpclib.Server('http://%s:%s' %(host, port))
264
+            rt = daemon.quit(passwd)
265
+            if rt == 'OK':
266
+                print 'Current daemon closed.'
267
+                server = Daemon((host, port), passwd=passwd)
268
+            else:
269
+                raise Exception(rt)
270
+        except Exception, e:
271
+            print >>sys.stderr, 'Failed to start daemon: %s' %e
272
+            return
273
+    print 'Running notification daemon...'
274
+    server.register_instance(Notifications(method, passwd=passwd))
275
+    server.serve_forever()
276
+
277
+
278
+def daemonize(PIDFILE='/tmp/inotify-daemon.pid'):
279
+    """
280
+    Forks current process into a daemon, there are several examples in the web for do this, but a
281
+    double fork is needed."""
282
+
283
+    # Do first fork.
284
+    try:
285
+        pid = os.fork()
286
+        if pid > 0:
287
+            # exit first parent
288
+            sys.exit(0)
289
+    except OSError, e:
290
+        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
291
+        sys.exit(1)
292
+
293
+    # make sure our executable is in absolute path
294
+    daemon_abs_path = os.path.join(os.path.abspath(os.curdir), sys.argv[0])
295
+    sys.argv[0] = daemon_abs_path
296
+
297
+    # Decouple from parent environment.
298
+    os.chdir("/")
299
+    os.setsid()
300
+    os.umask(0)
301
+
302
+    # Do second fork.
303
+    try:
304
+        pid = os.fork()
305
+        if pid > 0:
306
+            # exit from second parent, print eventual PID before
307
+            print "Daemon PID %d" % pid
308
+            open(PIDFILE,'w').write("%d"%pid)
309
+            sys.exit(0)
310
+    except OSError, e:
311
+        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
312
+        sys.exit(1)
313
+    # Now I am a daemon!
314
+
315
+if __name__ == '__main__':
316
+    # argument parsing
317
+    usage = __doc__
318
+    parser = optparse.OptionParser(usage=usage)
319
+    parser.add_option('-p', '--port', dest='port', type='int', 
320
+            help='Port to listen. [Default: %default]', default=7766)
321
+    parser.add_option('-H', '--host', dest='host',
322
+            help='Daemon hostname. [Default: %default]', default='localhost')
323
+    parser.add_option('-m', '--method', dest='method',
324
+            help="Notification method, available: 'libnotify', 'dbus' [Default: %default]",
325
+            default='libnotify')
326
+    parser.add_option('-P', '--passwd', dest='passwd',
327
+            help="Password for accept incoming notifications. [Default: %default]")
328
+    parser.add_option('-t', '--test', dest='test', action='store_true',
329
+            help='Send a test notification to an already running daemon and exit.',
330
+            default=False)
331
+    opts, args = parser.parse_args(sys.argv)
332
+
333
+    port = opts.port
334
+    host = opts.host
335
+    method = opts.method
336
+    passwd = opts.passwd or ''
337
+    
338
+    if opts.test:
339
+        daemon = xmlrpclib.Server('http://%s:%s' %(host, port))
340
+        print getattr(daemon, method)(passwd, 'This is a test')
341
+        sys.exit(0)
342
+
343
+    daemonize()
344
+    main(host=host, port=port, method=method, passwd=passwd)
345
+
346
+# vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100:

+ 0
- 1
sortfiles View File

@@ -1,5 +1,4 @@
1 1
 #!/bin/bash
2
-# Simple autosort for downloads
3 2
 find /riddlebox/Downloads/  -regextype posix-egrep -regex ".*\.(jpg|png|gif|jpeg|svg|tga|psd|jpe|bmp)$" -exec mv -n -t /riddlebox/miscimgs {} +
4 3
 find /riddlebox/Downloads/  -regextype posix-egrep -regex ".*\.(deb|run|bin|rpm|sh|py)$" -exec mv -n -t /riddlebox/misc {} +
5 4
 find /riddlebox/Downloads/  -regextype posix-egrep -regex ".*\.(diff|patch)$" -exec mv -n -t /riddlebox/misc {} +

Loading…
Cancel
Save