#!/bin/bash

  #CPU usage

  m=$(top -b -c -n 1)
  while read -r m
  do
      if [[ $m != *"top"* && $m != *"Cpu"* && $m != *"KiB Mem"* && $m != *"KiB Swap"* && $m != "" && $m != *"PID USER PR"* ]]; then
        var_cpu=$var_cpu$(awk '{print "cpu_usage_top{process=\""$12 " " $13 " " $14 "\", pid=\""$1"\"}", $9m}');
      fi
  done <<< "$m"
  curl -X POST -H  "Content-Type: text/plain" --data "$var_cpu
  " http://localhost:9091/metrics/job/top/instance/machine;
  
  # Memory use
  m=$(top -b -c -n 1)
  while read -r m
  do
      if [[ $m != *"top"* && $m != *"Cpu"* && $m != *"KiB Mem"* && $m != *"KiB Swap"* && $m != "" && $m != *"PID USER PR"* ]]; then
        var_memory=$var_memory$(awk '{print "memory_usage_top{process=\""$12 " " $13 " " $14 "\", pid=\""$1"\"}", $10m}');
      fi
  done <<< "$m"
  curl -X POST -H  "Content-Type: text/plain" --data "$var_memory
  " http://localhost:9091/metrics/job/top/instance/machine;
  
  # disk usage
  m=$(pidstat -dl 1 1)
  while read -r m
  do
      if [[ $m == *"Average:"* ]]; then
        disk_usage_write_stat=$disk_usage_write_stat$(awk '{print "disk_usage_write_stat{process=\""$8 " " $9 " " $10"\", pid=\""$3"\"}", $5m}');
      fi
  done <<< "$m"
  curl -X POST -H  "Content-Type: text/plain" --data "$disk_usage_write_stat
  " http://localhost:9091/metrics/job/top/instance/machine;
  
  m=$(pidstat -dl 1 1)
  while read -r m
  do
      if [[ $m == *"Average:"* ]]; then
        disk_usage_read_stat=$disk_usage_read_stat$(awk '{print "disk_usage_read_stat{process=\""$8 " " $9"\", pid=\""$3"\"}", $4m}');
      fi
  done <<< "$m"
  curl -X POST -H  "Content-Type: text/plain" --data "$disk_usage_read_stat
  " http://localhost:9091/metrics/job/top/instance/machine;
  
  # cores counter
  
  m=$(cat /proc/cpuinfo | grep processor | wc -l)
  curl -X POST -H  "Content-Type: text/plain" --data "core_count{cores= \"$m\" } $m
  " http://localhost:9091/metrics/job/top/instance/machine;
  
