#! /usr/bin/python3
#
# Copyright (c) 2010-2015 Liraz Siri <liraz@turnkeylinux.org>
#               2015-2021 TurnKey GNU/Linux <admin@turnkeylinux.org>
#
# This file is part of turnkey-sysinfo
#
# turnkey-sysinfo is open source software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
import os
import re
import subprocess
import time
from datetime import datetime

import netinfo
from libsysinfo import disk
from libsysinfo.memstats import MemoryStats

NIC_BLACKLIST = ["lo"]


def get_nics() -> list[tuple[str, str]]:
    nics = []

    for ifname in netinfo.get_ifnames():
        if ifname in NIC_BLACKLIST:
            continue

        nic = netinfo.InterfaceInfo(ifname)
        if nic.is_up and nic.address:
            nics.append((ifname, nic.address))

    nics.sort()
    return nics


def get_loadavg() -> float:
    return os.getloadavg()[0]


def get_pids() -> list[int]:
    return [
        int(dentry)
        for dentry in os.listdir("/proc")
        if re.match(r"\d+$", dentry)
    ]


def get_time_date() -> str:
    timezone = time.strftime("%Z", time.localtime())
    tz_info = f"(UTC{time.strftime('%z', time.localtime())})"
    if timezone != "UTC":
        tz_info = f"- {timezone} {tz_info}"
    time_string = f"%a %b %d %H:%M:%S %Y {tz_info}"
    return datetime.now().strftime(time_string)


def main() -> None:
    system_load = f"System load:  {get_loadavg():.2f}"

    processes = f"Processes:    {len(get_pids())}"
    disk_usage = f"Usage of /:   {disk.usage('/')}"

    memstats = MemoryStats()

    memory_usage = f"Memory usage:  {memstats.used_memory_percentage:.1f}%"
    swap_usage = f"Swap usage:    {memstats.used_swap_percentage:.1f}%"

    rows = []
    rows.append((system_load, memory_usage))
    rows.append((processes, swap_usage))

    all_nics = get_nics()
    if not all_nics:
        nics = ["Networking not configured"]
    else:
        nics = [f"IP address for {nic}: {address}" for nic, address in all_nics]

    column = [disk_usage]
    if nics:
        column.append(nics[0])
    # TODO rows' type is list[tuple[str, str]], but column is a list[str]
    rows.append(column)
    for nic in nics[1:]:
        rows.append(("", nic))

    print(f"System information for {get_time_date()}")
    print()
    max_col = max([len(row[0]) for row in rows])
    tpl = "  {:<{col}}   {}"
    for row in rows:
        print(tpl.format(row[0], row[1], col=max_col))

    if os.geteuid() == 0:
        try:
            tklbam_status = subprocess.run(
                ["tklbam-status"], capture_output=True, text=True
            ).stdout
        except FileNotFoundError:
            tklbam_status = "TKLBAM not installed."
        print()
        print(tklbam_status)


if __name__ == "__main__":
    main()
