#! /usr/bin/env python3

import os, sys, subprocess

class nfs_server_conf:
    """
     Diese Class installiert nur einen NFS Server mit Systemd voraussetzung ist das nsfv4 installiert ist
    """
    def __init__(self, nfs_srv_folders = ["/nfsroot/publicnfs","/nfsroot/datennfs"], nfs_config_file = "/etc/exports", allow_network = "192.168.50.0/25") -> None:
        if not os.geteuid()==0:
            raise PermissionError("Sie sind kein Root")
        self.nfs_srv_folders = nfs_srv_folders
        self.nfs_config_file = nfs_config_file
        self.allow_network = allow_network

    def mount_serverfolder(self):
        list_mountfiles = []
        for srv_folder in self.nfs_srv_folders:
            unit_mount_file = "/etc/systemd/system/" + os.path.basename(srv_folder) + ".mount"
            mountfile = os.path.basename(unit_mount_file)
            #mount Verzeichnis anlegen
            if os.path.exists(srv_folder):
                print("Das Verzeichnis", srv_folder,"ist bereits vorhanden !")
            else:
                os.makedirs(srv_folder, mode=1777)

            if os.path.exists(unit_mount_file) is True:
                print("Die Unit", unit_mount_file, "existiert bereits !", sep=" ")
            else:
                with open(unit_mount_file, "w") as unit_file:
                    print("""[Unit]\nDescription=Mount nfs Server Share\n[Mount]\nWhat={srv_folder}\nWhere={srv_point}\nType=None\nOptions=bind\n[Install]\nWantedBy=multi-user.target""".format(
                        srv_folder=srv_folder,
                        srv_point="/" + os.path.basename(srv_folder)), file=unit_file)
                    if subprocess.run(['systemctl', 'daemon-reload']).returncode == 0:
                        print("Systemed daemon-reload wurde ausgeführt")
                    else:
                         raise "Reloade konnte nicht ausgeführt werden."
            #Starte UnitFile
            list_mountfiles.append(mountfile)
            if subprocess.run(['systemctl', 'start', mountfile]).returncode == 0:
                print(mountfile, "wurde gestartet !", sep=" ")
            else:
                raise "Service" + mountfile +" konnte nicht gestart werden"
            
            if subprocess.run(['systemctl', 'enable', mountfile]).returncode == 0:
                print(mountfile, "wurde enabled !", sep=" ")
            else:
                raise "Service" + mountfile +" konnte nicht enabled werden"
        return list_mountfiles                               
                
    def nfs_server_conf(self):
        folder_count = []
        for srv_folder in self.nfs_srv_folders:
            index_count = 0
            with open(self.nfs_config_file,'r') as exportfs_file:
                exportfs_exist = []
                print(srv_folder)         
                for exportfs_line in exportfs_file.readlines(): 
                    checkline = exportfs_line.rstrip("\n")[0:len(srv_folder)]
                    if  checkline == srv_folder:
                        index_count += 1 
                folder_count.append({"folder_name": srv_folder, "count_exist":index_count})

        for folder_counting in folder_count:
            if folder_counting["count_exist"] > 0:
                print(folder_counting["folder_name"], "ist vorhanden in", self.nfs_config_file )
            else:
                os.path.abspath(folder_counting["folder_name"])
                with open(self.nfs_config_file, 'a') as add_exportfile:
                    print(os.path.dirname(folder_counting["folder_name"]), self.allow_network + "(rw,sync,insecure,root_squash,no_subtree_check,fsid=0)", file=add_exportfile)
                    print(folder_counting["folder_name"], self.allow_network + "(rw,sync,insecure,root_squash,no_subtree_check)", file=add_exportfile)
                print(folder_counting["folder_name"], "ist NICHT vorhanden in", self.nfs_config_file )

    def nfs_con_user(self):
        pass
#wait
    def start_nfs_server(self):
        unitname_nfsv4 = "nfsv4-server.service"
        if subprocess.run(['systemctl', 'restart', unitname_nfsv4]).returncode == 0:
                print(unitname_nfsv4, "wurde gestartet !", sep=" ")
        else:
                raise "Service" + unitname_nfsv4 +" konnte nicht gestart werden"
               
        if subprocess.run(['systemctl', 'enable', unitname_nfsv4]).returncode == 0:
                print(unitname_nfsv4, "wurde enabled !", sep=" ")
                return True
        else:
                raise "Service" + unitname_nfsv4 +" konnte nicht enabled werden"

    
    def main_install(self):
        nfs_server_conf.mount_serverfolder(self)
        nfs_server_conf.nfs_server_conf(self)
        nfs_server_conf.start_nfs_server(self)

    def __str__(self) -> str:
        pass

if __name__ == "__main__":
    my_nfs_server = nfs_server_conf(allow_network="*")
    my_nfs_server.main_install()
