#!/usr/bin/env python3
import os
from misc import bar, gig


# SYSTEM IS UP

# "up <time>\n"
uptime = os.popen('uptime -p').read()

# split to remove first word and newline
print("System is up \x1b[34m{}\x1b[0m".format(uptime[3:-1]))


# N USERS N TERMINALS

who = os.popen('w').read()

who = who.split('\n')[2:-1]
users = [0, 0]
for line in who:
    line = line.split()
    if line[2].startswith('tmux'):
        users[1] += 1
    else:
        users[0] += 1

print("{} users and {} terminals".format(*users))


# CPU LOADS

loads = os.popen("cat /proc/loadavg").read()
loads = loads.split(' ')[:3]
loads[0] = loads[0][:-1]
loads[1] = loads[1][:-1]

print("CPU: ", end='')

for load in loads:
    load = float(load)
    color = '\x1b[32m'
    if load > 1:
        color = '\x1b[31m'
    else:
        if load > 0.5:
            color = '\x1b[33m'

    print('{}{} '.format(color, load), end='')
print('\x1b[0m\n')


# MEMORY USAGE

free = os.popen("free").read().split('\n')

memory = free[1].split()
swap = free[2].split()

print(
    "Memory: {:.1f}GB out of {:.1f}GB (Swap {:.1f}/{:.1f})"
    .format(
        gig(memory[2]),
        gig(memory[1]),
        gig(swap[2]),
        gig(swap[1])
    )
)

print(bar(memory[2], memory[1], ['\x1b[93m=', '-']))
print()

# NETWORK ADAPTERS LIST

# get all cards
ip = os.popen('ip addr').read().split('\n')[:-1]

# get virtual cards
virtual = os.popen(
    "ls /sys/class/net -l | grep virtual | awk '{print $9}'").read().split('\n')

links = []
skip = False
nicNameLen = 0

for line in ip:
    line = line.split()

    if ':' in line[0]:
        if 'UP' in line[2]:
            eth = line[1][:-1]
            links.append([eth])
            if len(eth) > nicNameLen:
                nicNameLen = len(eth)
            skip = False
        else:
            skip = True

    if skip:
        continue

    if 'link' in line[0]:
        links[-1].append([line[1]])

    if 'inet' in line[0]:
        links[-1][-1].append(line[1].split('/'))

for eth in links:
    # skip virtual cards
    if eth[0] in virtual:
        continue

    print("{}:{} {} - \x1b[36m{}/{}\x1b[0m".format(
        eth[0],
        " "*(nicNameLen-len(eth[0])),
        eth[1][0],
        eth[1][1][0],
        eth[1][1][1]
    ))
print()
