#!/usr/bin/python3
import sys
import re
import os
import datetime
import paramiko
import getopt

class Mandant:

    def __init__(self, man, bdir, ldir, cdir, username, port):
        self.man = man
        self.cdir = cdir
        self.datei = os.path.join(cdir, f"{self.man}.cfg")
        self.bdir = bdir
        self.ldir = ldir
        self.username = username
        self.port = port
    
    def try_open(self):
        try:
            with open(self.datei, "r") as f:
                self.dat = f.readlines()
            return True
        except FileNotFoundError:
            return False
        
    def computer(self):
        comp_array = [line.split(":")[0] for line in self.dat]
        return comp_array
    
    def dirs(self, comp):
        dir_array = []
        for line in self.dat:
            if line.startswith(comp):
                dir_array = line.rstrip().split(":")[1].split(";")
                break
        return dir_array
    
    @staticmethod
    def today():
        return str(datetime.date.today())

    @staticmethod
    def source(r, v):
        return f"{r}:{v}/ "
    
    def dest(self, r, v):
        mod_v = v.replace("/", "-")[1:]
        dst = os.path.join(self.bdir, self.man, r, self.today(), mod_v)
        os.makedirs(dst, exist_ok=True)
        return dst

    def log(self, r, v):
        mod_v = v[1:]
        manlogdir = os.path.join(self.ldir, self.man, r, mod_v)
        os.makedirs(manlogdir, exist_ok=True)
        return os.path.join(manlogdir, self.today())
    
    @staticmethod
    def ssh_check(r, username, port):
        client = paramiko.SSHClient()
        client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        try:
            client.connect(r, username=username, port=port)
            return True
        except Exception as e:
            print(f"Fehler bei der SSH Verbindung {e}")
            return False

    def backup_dirs(self, r, username, port):
        for verzeichnis in self.dirs(r):
            if self.ssh_check(r, username, port):
                if "kim" in r:
                        cmd = f"rsync -azx --rsync-path='sudo rsync' {username}@{self.source(r, verzeichnis)} {self.dest(r, verzeichnis)} > {self.log(r, verzeichnis)}.0"
                else:
                        cmd = f"rsync -azx {username}@{self.source(r, verzeichnis)} {self.dest(r, verzeichnis)} > {self.log(r, verzeichnis)}.0"
            else:
                cmd = f"echo ssh error > {self.log(r, verzeichnis)}.1"
            print(cmd)
            os.system(cmd)

    def list_dirs(self, r):
        for verzeichnis in self.dirs(r):
            print(self.source(r, verzeichnis))

    def backup_mandant(self):
        for rechner in self.computer():
            self.backup_dirs(rechner, self.username, self.port)

if __name__ == "__main__":
    options, mandant = getopt.getopt(sys.argv[1:], 'r:l:u:p:')
    
    username = "root"
    port = "8472"

    for opt, arg in options:
        if opt == "-u":
            username = arg
        elif opt == "-p":
            port = arg
    
    if not mandant:
        print(f"{sys.argv[0]} (-r rechner|-l rechner) mandant")
    else:
        configdir = "/share/backup/config/"
        backupdir = "/share/backup/"
        logdir = "/var/log/backup"
        x = Mandant(mandant[0], backupdir, logdir, configdir, username, port)
        if x.try_open():
            if not options:
                x.backup_mandant()
            else:
                for opt, arg in options:
                    if opt in ('-r'):
                        x.backup_dirs(arg, username, port)
                    elif opt in ('-l'):
                        x.list_dirs(arg)
        else:
            print("can't open mandant file")
