"""
Module for managing Solaris logadm based log rotations.
"""

import logging
import shlex

import salt.utils.args
import salt.utils.decorators as decorators
import salt.utils.files
import salt.utils.stringutils

try:
    from shlex import quote as _quote_args  # pylint: disable=E0611
except ImportError:
    from pipes import quote as _quote_args


log = logging.getLogger(__name__)
default_conf = "/etc/logadm.conf"
option_toggles = {
    "-c": "copy",
    "-l": "localtime",
    "-N": "skip_missing",
}
option_flags = {
    "-A": "age",
    "-C": "count",
    "-a": "post_command",
    "-b": "pre_command",
    "-e": "mail_addr",
    "-E": "expire_command",
    "-g": "group",
    "-m": "mode",
    "-M": "rename_command",
    "-o": "owner",
    "-p": "period",
    "-P": "timestmp",
    "-R": "old_created_command",
    "-s": "size",
    "-S": "max_size",
    "-t": "template",
    "-T": "old_pattern",
    "-w": "entryname",
    "-z": "compress_count",
}


def __virtual__():
    """
    Only work on Solaris based systems
    """
    if "Solaris" in __grains__["os_family"]:
        return True
    return (
        False,
        "The logadm execution module cannot be loaded: only available on Solaris.",
    )


def _arg2opt(arg):
    """
    Turn a pass argument into the correct option
    """
    res = [o for o, a in option_toggles.items() if a == arg]
    res += [o for o, a in option_flags.items() if a == arg]
    return res[0] if res else None


def _parse_conf(conf_file=default_conf):
    """
    Parse a logadm configuration file.
    """
    ret = {}
    with salt.utils.files.fopen(conf_file, "r") as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line).strip()
            if not line:
                continue
            if line.startswith("#"):
                continue
            splitline = line.split(" ", 1)
            ret[splitline[0]] = splitline[1]
    return ret


def _parse_options(entry, options, include_unset=True):
    """
    Parse a logadm options string
    """
    log_cfg = {}
    options = shlex.split(options)
    if not options:
        return None

    ## identifier is entry or log?
    if entry.startswith("/"):
        log_cfg["log_file"] = entry
    else:
        log_cfg["entryname"] = entry

    ## parse options
    # NOTE: we loop over the options because values may exist multiple times
    index = 0
    while index < len(options):
        # log file
        if index in [0, (len(options) - 1)] and options[index].startswith("/"):
            log_cfg["log_file"] = options[index]

        # check if toggle option
        elif options[index] in option_toggles:
            log_cfg[option_toggles[options[index]]] = True

        # check if flag option
        elif options[index] in option_flags and (index + 1) <= len(options):
            log_cfg[option_flags[options[index]]] = (
                int(options[index + 1])
                if options[index + 1].isdigit()
                else options[index + 1]
            )
            index += 1

        # unknown options
        else:
            if "additional_options" not in log_cfg:
                log_cfg["additional_options"] = []
            if " " in options[index]:
                log_cfg["dditional_options"] = "'{}'".format(options[index])
            else:
                log_cfg["additional_options"].append(options[index])

        index += 1

    ## turn additional_options into string
    if "additional_options" in log_cfg:
        log_cfg["additional_options"] = " ".join(log_cfg["additional_options"])

    ## ensure we have a log_file
    # NOTE: logadm assumes logname is a file if no log_file is given
    if "log_file" not in log_cfg and "entryname" in log_cfg:
        log_cfg["log_file"] = log_cfg["entryname"]
        del log_cfg["entryname"]

    ## include unset
    if include_unset:
        # toggle optioons
        for name in option_toggles.values():
            if name not in log_cfg: