"""SSL tools."""

import os

from . import utils


class CertificateBackend(object):
    """Base class."""

    def __init__(self, config):
        """Set path to certificates."""
        self.config = config
        for base_dir in ["/etc/pki/tls", "/etc/ssl"]:
            if os.path.exists(base_dir):
                self.config.set(
                    "general", "tls_key_file",
                    "{}/private/%(hostname)s.key".format(base_dir))
                self.config.set(
                    "general", "tls_cert_file",
                    "{}/certs/%(hostname)s.cert".format(base_dir))
                return
        raise RuntimeError("Cannot find a directory to store certificate")


class SelfSignedCertificate(CertificateBackend):
    """Create a self signed certificate."""

    def create(self):
        """Create a certificate."""
        if os.path.exists(self.config.get("general", "tls_key_file")):
            if not self.config.getboolean("general", "force"):
                answer = utils.user_input(
                    "Overwrite the existing SSL certificate? (y/N) ")
                if not answer.lower().startswith("y"):
                    return
        utils.printcolor(
            "Generating new self-signed certificate", utils.YELLOW)
        utils.exec_cmd(
            "openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 "
            "-subj '/CN={}' -keyout {} -out {}".format(
                self.config.get("general", "hostname"),
                self.config.get("general", "tls_key_file"),
                self.config.get("general", "tls_cert_file"))
        )


def get_backend(config):
    """Return the appropriate backend."""
    return SelfSignedCertificate(config)

@@ -202,16 +202,81 @@
  config%0A
+        if not config.has_option(%22general%22, %22tls_key_file%22):%0A    
         
@@ -325,32 +325,36 @@
 %22%5D:%0A            
+  
+  
 if os.path.exist
@@ -374,32 +374,36 @@
                 
+    
 self.config.set(
@@ -415,32 +415,36 @@
                 
+   
+ 
 %22general%22, %22tls_
@@ -446,32 +446,36 @@
 %22tls_key_file%22,%0A
+    
                 
@@ -534,32 +534,36 @@
                 
+   
+ 
 self.config.set(
@@ -555,32 +555,36 @@
 elf.config.set(%0A
+    
                 
@@ -607,32 +607,36 @@
 tls_cert_file%22,%0A
+    
                 
@@ -694,39 +694,47 @@
                 
+    
 return%0A
+    
         raise Ru
@@ -792,16 +792,49 @@
 icate%22)%0A
+        else:%0A            return%0A
 %0A%0Aclass 

update SSL logic to accomodate pregenerated certificates