#!/usr/bin/env python3
import argparse
import os
from pathlib import Path

import subprocess as s
import sys
from n4d import client
import json


class CDC:
    def __init__(self, args):
        self.args = args
        self.sssconfigdest = Path("/etc/sssd/sssd.conf")
        self.sssconfigorig = Path("/usr/share/cdc/configs/sssd.conf")
        self.pamsssorig = Path("/usr/share/llx-pam-configs/diverted/sss.diverted")  # noqa: E501
        self.pamsssdest = Path("/usr/share/pam-configs/sss")
        self.keypath = Path("/etc/n4d/key")
        self.n4d_inbox_variable_path = Path("/var/lib/n4d/variables-inbox/ENABLE_CDC")  # noqa: E501

    def set_n4d_var(self, enabled=True):
        set_var = True
        result = s.run(["lliurex-version"], capture_output=True, text=True)
        if "client" in result.stdout:
            set_var = False
        with self.keypath.open("r") as fd:
            key = fd.readline().strip()
        c = client.Client("https://localhost:9779", key=key)
        try:
            c.get_methods()
        except client.ServerError:
            # Create variable to rean on start n4d Server
            if set_var:
                value = {}
                value["ENABLE_CDC"] = {"function": None,
                                       "package": "cdc",
                                       "description": "enable cdc",
                                       "value": enabled,
                                       "force_update": True}
                with self.n4d_inbox_variable_path.open("w") as fd:
                    json.dump(value, fd)
            else:
                c.PamnssPlugin.configure_nsswitch()
            return
        if set_var:
            c.set_variable("ENABLE_CDC", enabled)
        else:
            c.PamnssPlugin.configure_nsswitch()
        return

    def run(self):
        ldap_path = Path("/etc/ldap.conf")
        modules = []
        if ldap_path.exists():
            modules.append("fix_ldap")

        if self.args.e:
            if not self.sssconfigorig.exists():
                print("SSSD config not exists {}".format(str(self.sssconfigorig)))  # noqa: E501
                sys.exit(1)
            if not self.pamsssorig.exists():
                print("PAM config not exists {}".format(str(self.pamsssorig)))
                sys.exit(1)

            if not self.sssconfigdest.exists():
                os.link(str(self.sssconfigorig), str(self.sssconfigdest))
            if not self.pamsssdest.exists():
                os.link(str(self.pamsssorig), str(self.pamsssdest))
            modules.append("mkhomedir")
            modules.append("nss_lliurex")
            s.run(["pam-auth-update", "--package", "--enable", *modules],
                  capture_output=True, text=True)
            self.set_n4d_var(True)
        elif self.args.d:
            self.sssconfigdest.unlink(True)
            self.pamsssdest.unlink(True)
            modules.append("nss_lliurex")
            s.run(["pam-auth-update", "--package", "--remove", *modules],
                  capture_output=True, text=True)
            self.set_n4d_var(False)
        elif self.args.t:
            if self.sssconfigdest.exists():
                print("True")
                sys.exit(0)
            else:
                print("False")
                sys.exit(1)
        sys.exit(0)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", action="store_true", help="Enable CDC")
    parser.add_argument("-d", action="store_true", help="Disable CDC")
    parser.add_argument("-t", action="store_true", help="State of CDC")
    args = parser.parse_args()
    cdc = CDC(args)
    cdc.run()
