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

require 'json'
require_relative '.utils'

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

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

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

process_list = JSON.parse(`ps auxww -U \`id -u\` --libxo json`)['process-information']['process']
for process in process_list
  if process['command'].include?('steamwebhelper') && process['state'] != 'Z'
    pid = process['pid'].to_i
    pwarn "Killing leftover steamwebhelper process: #{pid}"
    Process.kill(:KILL, pid)
  end
end
