#!/bin/sh
# Copyright (C) 2014 Julien Bonjean <julien@bonjean.info>

# This program is free 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.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

TYPE="${BLOCK_INSTANCE:-mem}"

if [ ${BLOCK_BUTTON--1} -gt 0 ]; then
    i3-sensible-terminal -r floating-term --geometry 100x54 -e 'top -d 0.1'
fi

awk -v type=$TYPE '
BEGIN {
    swap_total=1
    mem_total=1
}
/^MemTotal:/ {
	mem_total=$2
}
/^MemFree:/ {
	mem_free=$2
}
/^Buffers:/ {
	mem_free+=$2
}
/^Cached:/ {
	mem_free+=$2
}
/^SwapTotal:/ {
	swap_total=$2
}
/^SwapFree:/ {
	swap_free=$2
}
END {
	if (type == "swap") {
        swap_perc = (swap_total - swap_free) / swap_total * 100
		printf("%.0f%\n", swap_perc)
		printf("%.0f%\n", swap_perc)	
		perc = swap_perc
	}
	else{
        mem_perc  = (mem_total - mem_free) / mem_total * 100
		printf("%.0f%\n", mem_perc)
		printf("%.0f%\n", mem_perc)
	    perc = mem_perc
	}

    if (perc > 80)
        print "#FFCB00"
    else if (perc > 60)
        print "#FFCB00"
}
' /proc/meminfo
