from fabric import Connection
import colorama

# assume you log into remote os with ssh, and can run "sudo su - oracle" without asking password
username = "your_acct"
password = "your_pswd"

colorama.init(autoreset=True)

command = """
mem_tot=$(grep MemTotal /proc/meminfo | awk '{printf "%.1f",$2/1024}')
page_tab=$(grep PageTables /proc/meminfo | awk '{printf "%.1f",$2/1024}')
asmm_shr=$(echo "ipcs -m | grep oracle" | sudo su - oracle | awk '{print $5}' | awk '{ sum+=$1 } END { printf "%.1f",sum/1024/1024 }')
amm_shr=$(df -Pk /dev/shm | sed -n '2p' | awk '{printf "%.1f",$3/1024}')
shr_tot=$(echo - | awk "{print $asmm_shr + $amm_shr}")
echo "$mem_tot $page_tab $asmm_shr $amm_shr $shr_tot"
# printf "%15.1f%15.1f%15.1f%15.1f%15.1f" $mem_tot $page_tab $asmm_shr $amm_shr $shr_tot
"""

def get_mem_info(p_host, p_cmd):
    try:
        c = Connection(host=username + '@' + p_host, connect_kwargs={"password": password})
        result = c.run(p_cmd, pty=True, hide=True)
        (mem_tot, page_tab, asmm_shr, amm_shr, shr_tot) = result.stdout.split()
        page_tab_ratio=float(page_tab)/float(mem_tot)
        if 0.0 <= page_tab_ratio < 0.1:
            print(f'{p_host:<30}{mem_tot:>15}{page_tab:>15}{asmm_shr:>15}{amm_shr:>15}{shr_tot:>15}')
        elif 0.1 <= page_tab_ratio < 0.3:
            print(f'{p_host:<30}{mem_tot:>15}{colorama.Fore.YELLOW}{page_tab:>15}{colorama.Fore.WHITE}{asmm_shr:>15}{amm_shr:>15}{shr_tot:>15}')
        else:
            print(f'{p_host:<30}{mem_tot:>15}{colorama.Fore.RED}{page_tab:>15}{colorama.Fore.WHITE}{asmm_shr:>15}{amm_shr:>15}{shr_tot:>15}')

    except Exception as e:
        print(f'{p_host:<30}{"Error: "}{e}')
        print(e)

db_inv = open("inv/fab_inv.txt")
lines = db_inv.readlines()
print(f'{"HOSTNAME":<30}{"MEM_TOTAL":>15}{"PAGE_TAB":>15}{"ASMM_SHR":>15}{"AMM_SHR":>15}{"SHR_TOT":>15}')
for line in lines:
    if line[0:1] != '#':
        (v_host) = line.strip('\n')
        get_mem_info(v_host, command)