#!/bin/sh -e

__memory_detail() {
  if [ "$(uname)" = "OpenBSD" -o "$(uname)" = "FreeBSD" -o "$(uname)" = "NetBSD" ]; then
    # OpenBSD / FreeBSD / NetBSD
    top -b -d 1
  elif [ "$(uname)" = "Darwin" ]; then
    # macOS
    top -l 1 -s 0 -n 0 | grep PhysMem
  else
    # Linux
    free
  fi
}

__memory() {
  local total="" free="" unit_total="" unit_free=""
  local total_mb=0 free_mb=0 used_mb=0

  case "$(uname)" in
    Linux)
      while read -r name value _; do
        case "$name" in
          MemTotal:*) total=$((value/1024));;
          MemFree:*) free=$((value/1024));;
          Buffers:*) free=$((free + value/1024));;
          Cached:*) free=$((free + value/1024));;
        esac
      done < /proc/meminfo
      used_mb=$((total - free))
      ;;
    OpenBSD)
      total=$(($(sysctl -n hw.physmem) / 1024 / 1024))
      used_mb=$(vmstat | tail -1 | awk '{print substr($3, 1, length($3)-1)}')
      ;;
    NetBSD)
      total=$(($(sysctl -n hw.physmem64) / 1024 / 1024))
      used_mb=$(($(vmstat | tail -1 | awk '{print substr($3, 1, length($3))}') / 1024))
      ;;
    FreeBSD)
      total=$(($(sysctl -n hw.realmem) / 1024 / 1024))
      pagesize=$(sysctl -n hw.pagesize)
      inactive_count=$(sysctl -n vm.stats.vm.v_inactive_count)
      free_mb=$((inactive_count * pagesize / 1024 / 1024))
      used_mb=$((total - free_mb))
      ;;
    Darwin)
      total=$(printf "%.1f" "$(echo "$(sysctl -n hw.memsize_usable) / 1024 / 1024" | bc -l)")
      used_mb=$(printf "%.1f" "$(echo "$(vm_stat | grep 'Pages active' | awk '{print $3}') * 4096 / (1024 * 1024)" | bc -l)")
      ;;
  esac

  if [ $total -ge 1024 ]; then
    total=$(printf "%.1f" $(echo "$total / 1024" | bc -l))
    unit_total="G"
  else
    unit_total="M"
  fi

  if [ $used_mb -ge 1024 ]; then
    used_mb=$(printf "%.1f" $(echo "$used_mb / 1024" | bc -l))
    unit_used="G"
  else
    unit_used="M"
  fi

  color b b W; printf "%s%siB" "$used_mb" "$unit_used"; color -; color b b W; printf "/%s%siB" "$total" "$unit_total"; color --
}