#!/usr/bin/env ruby
# encoding: UTF-8

require 'json'
require_relative '.utils'

PID_FILE = File.join(ENV['HOME'], '.steam/steam.pid')

steam_pid = begin
  File.read(PID_FILE).to_i
rescue Errno::ENOENT
  pwarn 'No pid file found'
  nil
end

if steam_pid
  begin
    Process.kill(:KILL, steam_pid)
    begin
      Process.wait(steam_pid)
    rescue Errno::ECHILD
      # ?
    end
    File.unlink(PID_FILE)
  rescue Errno::ESRCH
    pwarn 'Steam is not running'
  end
end

leftovers = []
leftovers << steam_pid if steam_pid

processes = JSON.parse(`ps ww -o pid,ppid,state,command -U $(id -u) --libxo json`)['process-information']['process']

while true
  k = 0
  for process in processes
    cmd  = process['command']
    ppid = process['ppid'].to_i
    pid  = process['pid' ].to_i
    if (leftovers.include?(ppid) || cmd.include?('steamwebhelper')) && !leftovers.include?(pid) && process['state'][0] != 'Z'
      pwarn "Killing leftover process: #{pid} (#{process['command'][0...60]})"
      begin
        Process.kill(:KILL, pid)
      rescue Errno::ESRCH
        # meh
      end
      leftovers << pid
      k += 1
    end
  end
  break if k == 0
end
