#!/usr/bin/env python

from __future__ import division
from __future__ import print_function

import subprocess

GREEN = '\033[0;32m'
YELLOW = '\033[0;33m'
RESET = '\033[0m'

def ascii_bar(value, max_value, color=GREEN, width=27, unit='', end='\n'):
    width = int(width)
    if max_value > 0:
        ratio = float(value) / max_value
        print(RESET, end='')
        print('[', end='')
        print(color, end='')
        print('|' * int(ratio * width), end='')
        print(' ' * (width - int(ratio * width)), end='')
        print(RESET, end='')
        print('] ', end='')
        print('%5.1f / %5.1f%s' % (value, max_value, unit), end='')
    print('', end=end)


def main(width=27):
    lines = subprocess.check_output(['free', '-m'])
    if isinstance(lines, bytes):
        lines = lines.decode()
    lines = lines.strip().split('\n')
    mem, swap = lines[1], lines[2]

    mem_total, mem_used, mem_free, mem_shared, mem_buffcache, mem_avail = map(int, mem.split()[1:])
    swap_total, swap_used, swap_free = map(int, swap.split()[1:])

    print("Mem : ", end='')
    ascii_bar((mem_used) / 1024., mem_total / 1024.,
              unit=' G', width=width, end='')
    print("      ", end = '')
    print("Swap: ", end='')
    ascii_bar((swap_used) / 1024., swap_total / 1024.,
              color=YELLOW, unit=' G', width=width)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--width', default=27, type=int)
    args = parser.parse_args()

    main(**vars(args))
