summaryrefslogtreecommitdiff
path: root/ryrestore.py
blob: 7eee5948f5934fc980b681d11fce83af481f93ca (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
#!/usr/bin/env python

# ryrestore -- restore script for rybackup, rsync based backup script
#              with rotating backup-snapshots
# Copyright (C) 2010 Adrian C. <anrxc sysphere.org>

# 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.

# restore
#   % ~/.backup/ryrestore.py /home/user/.zshrc # restore a file
#   % ~/.backup/ryrestore.py /home/user/mail/  # restore a directory


from sys import argv
from subprocess import call
from datetime import datetime
from os import getuid, path, listdir
from rybackup import bak, bin, mount


# Functions
#
# Managing backup snapshots
def select(source):
    snapshots = listdir(source)

    # Present the selection to the user, with numbered IDs
    for index, directory in enumerate(snapshots):
        mtime = datetime.fromtimestamp(path.getmtime(path.join(source, snapshots[index])))
        print "%s: %s [%s]" % (index, directory, mtime)

    # Get ID of the backup snapshot from which to restore
    return snapshots[int(raw_input("\nSnapshot: "))]


# Rsync backup restoration
def restore(source, destination):
    try:
        bsnap = select(source)
    except KeyboardInterrupt:
        print "\nError: user initiated exit"
        return
    except Exception, error:
        print "Error: incorrect snapshot ID or backup source\nDebug:", error
        return

    rsyncopt = (     # Mirroring options
        "--archive", #  use the archive mode,
        "--verbose", #  increase verbosity
    )

    # Restore from backup with rsync
    call("%s %s %s %s" % (bin['rsync'], " ".join(rsyncopt),
                          path.join(source, bsnap, destination[1:]),
                          destination), shell=True)


# Backup restore procedure
def main():
    usage = "Usage: %s {path}" % path.split(argv[0])[1]

    if getuid() != 0:
        raise SystemExit("Error: super user privileges required")
    try:
        if argv[1] != None:
            mount("mount")
            restore(bak['dst'], argv[1])
            mount("umount")
    except IndexError:
        raise SystemExit(usage)

if __name__ == "__main__":
    main()