restructuring code
[sitarba.git] / shbackup.py
index 41b24fe125686121c4a082d788546d8a66b27dc7..e1f038d559708119baa96f8b2522ee4397ea68b0 100755 (executable)
@@ -9,6 +9,41 @@ import subprocess
 import random, re
 
 
+Mode = ["full", "incr", "diff"]
+
+Epoch = { "hour" : datetime.timedelta(0, 3600), \
+        "day" : datetime.timedelta(1), \
+        "week" : datetime.timedelta(7), \
+        "month" : datetime.timedelta(30), \
+        "year" : datetime.timedelta(365) }
+
+class Backup:
+    """A single backup has a date, an epoch and a mode."""
+
+    def __init__(self, date, epoch, mode):
+        self.date = date
+        self.epoch = epoch
+        self.mode = mode
+
+    def __str__(self):
+        return "[date: " + self.date.ctime() + \
+                ", epoch: " + self.epoch + \
+                ", mode: " + self.mode + "]"
+
+    @staticmethod
+    def getDirName(date, epoch, mode):
+        """Get directory name of backup by given properties."""
+        return date.strftime("%Y%m%d-%H%M") + "-" + epoch + "-" + mode
+
+    @staticmethod
+    def isBackupDir(dirname):
+        """Is directory a backup directory?"""
+        p = re.compile(r'^\d\d\d\d\d\d\d\d-\d\d\d\d-\w+-\w+$')
+        return p.match(dirname)
+
+
+
+
 class Config:
     """Encapsules the configuration for the backup program."""
 
@@ -51,6 +86,8 @@ class Config:
     def read(self, filename):
         """Read configuration from file"""
 
+        if not os.path.isfile(filename):
+            raise Config.ReadException("No file '" + filename + "'.")
 
         config = configparser.RawConfigParser()
         config.read(filename)
@@ -123,39 +160,6 @@ class Config:
             self.lastchecksum = None
 
 
-Mode = ["full", "incr", "diff"]
-
-Epoch = { "hour" : datetime.timedelta(0, 3600), \
-        "day" : datetime.timedelta(1), \
-        "week" : datetime.timedelta(7), \
-        "month" : datetime.timedelta(30), \
-        "year" : datetime.timedelta(365) }
-
-class Backup:
-    """A single backup has a date, an epoch and a mode."""
-
-    def __init__(self, date, epoch, mode):
-        self.date = date
-        self.epoch = epoch
-        self.mode = mode
-
-    def __str__(self):
-        return "[date: " + self.date.ctime() + \
-                ", epoch: " + self.epoch + \
-                ", mode: " + self.mode + "]"
-
-    @staticmethod
-    def getDirName(date, epoch, mode):
-        """Get directory name of backup by given properties."""
-        return date.strftime("%Y%m%d-%H%M") + "-" + epoch + "-" + mode
-
-    @staticmethod
-    def isBackupDir(dirname):
-        """Is directory a backup directory?"""
-        p = re.compile(r'^\d\d\d\d\d\d\d\d-\d\d\d\d-\w+-\w+$')
-        return p.match(dirname)
-
-
 class BackupManager:
     """List and create backups"""
 
@@ -278,7 +282,7 @@ class BackupManager:
         mode = self.conf.epochmodes[epoch]
         print("Making a backup. Epoch: " + epoch + ", mode: " + mode)
 
-        oldfullbackups = [ b for b in oldbackups if b.mode=="full" ]
+        oldfullbackups = [ b for b in oldbackups if b.mode == "full" ]
 
         # No old full backups existing
         if mode != "full" and len(oldfullbackups)==0:
@@ -351,15 +355,51 @@ class BackupManager:
                 shutil.rmtree(os.path.join(basedir, d))
 
 
+def printUsage():
+    """Print --help text"""
+
+    print("shbackup - a simple backup solution.")
+    print("")
+    print("Usage:")
+    print("  " + sys.argv[0] + " [-C <configfile>")
+    print("  " + sys.argv[0] + " --help")
+    print("")
+    print("Options:")
+    print("  -C <configfile>        default: /etc/shbackup.conf")
+
+
 if __name__ == "__main__":
 
-    conffn = "shbackup.conf"
-    if len(sys.argv) > 1:
-        conffn = sys.argv[1]
+    conffn = "/etc/shbackup.conf"
+
+    i = 0
+    while i < len(sys.argv)-1:
+        i += 1
+        opt = sys.argv[i]
+
+        if opt in ["-h", "--help"]:
+            printUsage()
+            exit(0)
+
+        elif opt in ["-C", "--config"]:
+            i += 1
+            conffn = sys.argv[i]
+            continue
+
+        else:
+            print("Unknown option: " + opt)
+            exit(1)
+
+    try:
+        man = BackupManager(conffn)
+        man.backup()
+        man.prune()
 
-    man = BackupManager(conffn)
-    man.backup()
-    man.prune()
+    except Config.ReadException as e:
+        print("Error reading config file: ", end="")
+        for a in e.args:
+            print(a, end=" ")
+        print()