#!/usr/bin/python3
#
# msec: helper tools
#

import os
import stat
import sys
import time
import locale
import subprocess

# localization
import gettext
try:
    gettext.install("msec")
except IOError:
    _ = str

# constants
FIREWALL_CMD = "drakfirewall &"
UPDATE_CMD = "MageiaUpdate &"

def find_firewall_info(log):
    """Finds information about firewall"""
    # read firewall settings
    firewall_entries = []
    try:
        p = subprocess.run(["iptables", "-S"], capture_output=True)
        data = p.stdout.decode('utf-8')
        for l in data.splitlines():
            if l[:3] == "-A ":
                firewall_entries.append(l.strip())
    except OSError as e:
        log.error(_("Unable to parse firewall configuration: %s") % e)
    # not find out if the firewall is enabled
    if len(firewall_entries) == 0:
        firewall_status = _("Disabled")
    else:
        firewall_status = _("Enabled, with %d rules") % len(firewall_entries)
    return firewall_status

def get_updates_status(log, updatedir="/var/lib/urpmi"):
    """Get current update status"""
    # just find out the modification time of /var/lib/urpmi
    try:
        ret = os.stat(updatedir)
        updated = time.localtime(ret[stat.ST_MTIME])
        updated_s = time.strftime(locale.nl_langinfo(locale.D_T_FMT), updated)
        status = _("Last updated: %s") % updated_s
    except OSError as e:
        log.error(_("Unable to access %s: %s") % (updatedir, e))
        status = _("Unable to determine update status")
    return status

def periodic_check_status(log):
    """Determines the state of last periodic checks"""
    checks = []
    for check in [ "daily", "weekly", "monthly", "manual" ]:
        current_log = "/var/log/security/mail.%s.today" % check
        if os.access(current_log, os.R_OK):
            ret = os.stat(current_log)
            last_run = time.localtime(ret[stat.ST_MTIME])
            updated_s = time.strftime(locale.nl_langinfo(locale.D_T_FMT), last_run)
            checks.append((check, current_log, last_run, updated_s))
        else:
            checks.append((check, current_log, None, None))
    return checks
