require 'json'

$file = File.expand_path("../wiki_pages.json", __FILE__)
def main
  puts "read content from file #{File.size($file)}[#{File.size($file).to_hmsize}]"
  json = IO.read($file)
  sleep 30

  puts "parse json string to object"
  obj = JSON.parse(json)
  sleep 30

  puts "set string&object to nil, and sleep 30 min to check the memory usage."
  json = nil
  obj = nil
end

####  Helpers >>>
class Numeric
  def to_hmsize
    if self > 1024 ** 3
      "#{(self * 1.0 / (1024 ** 3)).round(2)} GB"
    elsif self > 1024 ** 2
      "#{(self * 1.0 / (1024 ** 2)).round(2)} MB"
    end
  end
  def to_hmtime
    "#{self / 60}m#{self % 60}s"
  end
end

def get_total_mem
  if RUBY_PLATFORM.index("linux")
    `awk '/MemTotal/ {print $2}' /proc/meminfo`.strip.to_i * 1024
  elsif RUBY_PLATFORM.index("darwin")
    `sysctl -a | grep mem | grep hw.memsize | awk '{print $2}'`.strip.to_i
  end
end
$total_mem = get_total_mem
def free_mem
  if RUBY_PLATFORM.index("linux")
    (`free -b | grep Mem | awk '{print $4}'`.strip.to_i)
  elsif RUBY_PLATFORM.index("darwin")
    $total_mem - `ps -caxm -orss= | awk '{ sum += $1 } END { print sum }'`.strip.to_i * 1024
  end
end

if !File.exists?($file)
  open($file, 'w') do |f|
    array = []
    radix = RUBY_PLATFORM.index("darwin") ? 10000 : 1500
    ($total_mem / radix).times.each do |i|
      array << {pageid: i, title: "title of #{i}", pagename: "pagename_of_#{i}"}
    end
    f.puts array.to_json
  end
  puts "created a json file: #{File.size($file)}[#{File.size($file).to_hmsize}]"
  puts "init the json file at the first launch, please run again."
  exit
end

puts RUBY_DESCRIPTION
puts Time.now

require 'objspace'

Thread.new do
  started = Time.now.to_i
  total_mem = $total_mem.to_hmsize
  puts "Memory: \e[1;32mProcess RSS\e[0m/\e[1;34mSystem Total Memory\e[0m/\e[1;31mSystem Free Memory\e[0m"
  while true
    sys_mem = (`ps -o rss= -p #{Process.pid}`.strip.to_i * 1024).to_hmsize
    objspace_mem = ObjectSpace.memsize_of_all.to_hmsize
    puts "#{(Time.now.to_i - started).to_hmtime} #{$$}\tMemory:\e[1;32m#{sys_mem}\e[0m/\e[1;34m#{total_mem}\e[0m/\e[1;31m#{free_mem.to_hmsize}\e[0m, objspace_mem:#{objspace_mem}"
    sleep 3
    GC.start
  end
end
####  Helpers <<<<

sleep 10
main
sleep 1800
