#!/usr/bin/python
import os
import subprocess
import sys

PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'  
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'

def make_bold(string):
    return '{:s}{:s}{:s}'.format(BOLD, string, END)

def get_ipv4_addr(interface):
    cmd = 'ifconfig {:s}'.format(interface)
    for line in subprocess.check_output(cmd, shell=True).split('\n'):
        if line.strip().startswith('inet addr:'):
            return line.split()[1][5:]
    else:
        return '{:s}NO IP ASSIGNED{:s}'.format(RED, END)

def get_fs_usage(mount_point):
    cmd = 'df -h | grep {:s}'.format(mount_point)
    try:
        line = subprocess.check_output(cmd, shell=True).split('\n')[0]
    except IndexError:
        return '{:s}MOUNT POINT NOT FOUND{:s}'.format(RED, END)
    line_tokens = line.split()
    
    usage_percent = int(line_tokens[4][:-1])
    percent_str = '{:s}{:d}%{:s}'.format(BOLD, usage_percent, END)
    if usage_percent > 90:
        percent_str = '{:s}{:s}{:d}%{:s}'.format(BOLD, RED, usage_percent, END)
    elif usage_percent > 70:
        percent_str = '{:s}{:s}{:d}%{:s}'.format(BOLD, YELLOW, usage_percent, END)
    
    
    output = '{:10s} ({:<9s}) - {:>4s} of {:>4s} [ {:s} ] used; '\
             '{:>4s} available'.format(line_tokens[5], line_tokens[0], 
                                       line_tokens[2], line_tokens[1],
                                       percent_str, line_tokens[3])
    return output


def main():
    """ This is a custom script I wrote to run on at login on phalanx
    and give me some system overview information.
    """

    rows, columns = os.popen('stty size', 'r').read().split()
    rows = int(rows)
    columns = int(columns)

    hostname = subprocess.check_output('hostname', shell=True).strip()

    ip_addr = get_ipv4_addr('enp3s0')
    root_stats = get_fs_usage('/dev/sda2')
    storage_stats = get_fs_usage('/dev/md0')

    print YELLOW + BOLD + '       _           _                  '
    print '      | |         | |                 '
    print ' _ __ | |__   __ _| | __ _ _ __ __  __'
    print "| '_ \| '_ \ / _` | |/ _` | '_ \\ \/ /"
    print '| |_) | | | | (_| | | (_| | | | |>  < '
    print "| .__/|_| |_|\__,_|_|\__,_|_| |_/_/\_\ "
    print '| |                                   '
    print '|_|                                   ' + END
    print PURPLE + BOLD + '-' * columns + END
    print
    print '{:<17s} {:s}   {:s} {:s}'.format(make_bold('Hostname:'), hostname, 
                                            make_bold('IP:'), ip_addr)
    print '{:<17s} {:s}'.format(make_bold('Storage:'), root_stats)
    print '{:<17s} {:s}'.format(make_bold(' '), storage_stats)
    print

    print PURPLE + BOLD + '-' * columns + END
    print
    print subprocess.check_output('w -i', shell=True)
    print PURPLE + BOLD + '-' * columns + END
    print

if __name__ == '__main__':
    sys.exit(main())
