#!/usr/bin/python3

import json, os

old_config     = "/etc/astra-syslog.conf.back"
current_config = "/etc/astra-syslog.conf"
new_config     = "/etc/astra-syslog.conf.dpkg-dist"

default_settings_dir = "/usr/share/syslog-ng-mod-astra/event-settings"
depricated_events = {
    "adding-user-to-group-alternative": "{}/user-groups/adding-user-to-group-alternative".format(default_settings_dir),
    "mounted-device-syscall": "{}/system/mounted-device-syscall".format(default_settings_dir),
    "unmounted-device-syscall": "{}/system/unmounted-device-syscall".format(default_settings_dir),
    "mounted-device-udisksd": "{}/system/mounted-device-udisksd".format(default_settings_dir),
    "unmounted-device-udisksd": "{}/system/unmounted-device-udisksd".format(default_settings_dir),
}

def remove_depricated_events(current_settings):
    for event, path in depricated_events.items():
        current_settings.pop(event, None)
        try:
            os.remove(path)
        except:
            pass

if __name__ == "__main__":
    old_settings     = {}
    current_settings = {}
    new_settings     = {}

    try:
        with open(old_config, "r") as file:
            try:
                old_settings = json.load(file)
            except:
                pass
    except:
        pass

    try:
        with open(new_config, "r") as file:
            try:
                new_settings = json.load(file)
            except:
                pass
    except:
        pass

    try:
        with open(current_config, "r") as file:
            try:
                current_settings = json.load(file)
            except Exception as e:
                print(e)
            else:
                current_settings.update(old_settings)
                if new_settings:
                    new_settings.update(current_settings)
    except Exception as e:
        print(e)
    try:
        with open(current_config, "w") as file:
            try:
                settings = current_settings if not new_settings else new_settings
                remove_depricated_events(settings)
                json.dump(settings, file, indent=4)
                file.write("\n")
            except Exception as e:
                print(e)
    except Exception as e:
        print(e)

    try:
        os.remove(old_config)
    except:
        pass
    try:
        os.remove(new_config)
    except:
        pass
