import batou.component
import batou.lib.file


class HTTPBasicAuth(batou.component.Component):
    """A glueing component for managing http_basic_auth auth strings.

    This component _does not_ generate the htpasswd string itself, but
    requires a pre-compiled one (stored into secrets). You may use

    mkpasswd -R 100000 -m sha-512 <password> <salt>

    for generating the passwordsection. General structure of entry is like
    <username>:<generated_password_string>

    Usage::

        from batou_ext.http import HTTPBasicAuth

        self += batou_ext.http.HTTPBasicAuth(
            "myauth",
            username="joe",
            password="secret",
            basic_auth_string="joe:$apr1$Ma0Fc6pW$Kl5dV4ecBXH12gDieRHVq.")

    Alternatively, if you want to use Flyingcircus' autogenerated http_auth
    file based on project configuration, just use::

        self += batou_ext.http.HTTPBasicAuth(fcio_auth=True)

    """

    _required_params_ = {"env_name": "test", "basic_auth_string": "secret"}
    env_name = None
    fcio_auth = batou.component.Attribute("literal", default=False)
    username = None
    password = None
    basic_auth_string = None
    providing = batou.component.Attribute("literal", default=True)

    def configure(self):
        if self.providing:
            self.provide("http_basic_auth", self)
        if self.fcio_auth:
            self.path = "/etc/local/nginx/htpasswd_fcio_users"
        else:
            self._deploy_customer_http_auth_file()

    def _deploy_customer_http_auth_file(self):
        if self.env_name is None:
            raise ValueError(
                "You need to define an environment name for "
                "your http_baisc_auth-file"
            )
        self += batou.lib.file.File(
            "htpasswd_{}".format(self.env_name), content=self.basic_auth_string
        )
        self.path = self._.path
