#!/usr/local/bin/ruby
# So this file can be used as a command
#
#
=begin
 ******************************************************************************
 * Copyright 1990-2009 MBARI
 * MBARI Proprietary Information. All rights reserved.
 ******************************************************************************
 * Summary  : stop command provides a quick way to kill the executive and
 *            supervisor process from the command line.
 * Filename : stop.rb
 * Author   : Henthorn
 * Project  : Benthic Rover
 * Version  : 1
 * Created  : May 2010
 * Modified :
 ******************************************************************************
=end

##
# Refer to Rover-code home directory as base
#
require "#{ENV['ROVER_HOME']}/utils/rover_environment"
#

require 'utils/misc'
require 'device/relay_board'

#####
# Use a RelayMan object to turn all the components off
#
def all_off
  puts("Components powering down...")
  rm = RelayMan.new
  rm.allOff
  system("stir OFF")
end
#####


#####
# Use 'kill' to stop the processes with the given PIDs
# pids is an array.
#
def kill_it(pids)
  return nil unless (pids)

  pids.each { |pid|
    cmd = "kill #{pid}"
    puts(cmd)
    system("kill #{pid}")
  }
  true
end
#####


#####
# Main script.
#  (1) Look for 'executive' and use 'kill' to stop it if found.
#  (2) Look for 'supervisor' and use 'kill' to stop it if found.
#  (3) Use RelayMan to turn all components off.
#
epids = nil
if (epids = Misc.running?("/executive"))
  puts("Found #{epids.length} executives...")
  kill_it(epids)
else
  puts("No executive processes found...")
end

spids = nil
if (spids = Misc.running?("/supervisor.rb"))
  puts("Found #{spids.length} supervisors...")
  kill_it(spids)
else
  puts("No supervisor processes found...")
end

puts("Cutting power to components...")
all_off

puts("Done")

#####
