#!/usr/local/bin/ruby
#
# auto_rover launch script and watchdog
#
# This script attempts to recover from unexplained
# bug where the rover mission main starts but crashes
# without a backtrace when creating the Rover.instance
#
# Run the main script in the background then monitor
# the process. If the process dies, simply restart it.
#

# Launch the mission script in the background
# Return true if successful, otherwise false.
#
def launch_it
  # Launch the main script
  #
  rover_cmd = "/cf/rover/lib/main.rb -f /cf/rover/lib/auto_rover.rb | tee -a /cf/rover/logs/auto_rover.log &"
#  rover_cmd = "tail -f /cf/rover/logs/auto_rover.log &"

  puts(rover_cmd)
  unless system(rover_cmd)
    puts("!! autorun.rb failed to launch the rover mission")
    puts("!! #{rover_cmd}")
    return false
  end
  return true
end

# Find the mission background process
# Return true if found, otherwise false.
#
def find_it
  pid = 0

  # Execute the grep command
  prc = `ps | grep main.rb | grep -v grep`
#  prc = `ps | grep tail | grep -v grep`
  
  # Look for the process in the result
  lines = prc.split('\n')

  if (lines.length > 0)
    lines.each { |line|
      tokens = line.split if line
      pid = tokens[0].to_i if tokens

      # Process found
      if (pid > 0)
#        puts("autorun: Mission still running: #{pid}")
        return true
      end
    }
  else
    puts("autorun: Mission process #{pid} not found")
  end
  return false
end

# Continually look for the mission process.
# If not found (i.e., it crashed) restart it
#
def watch_it
  while (true)
    sleep(120)
    unless (find_it)
      puts("autorun: Mission process #{pid} has exited, restarting...")
      launch_it
    end
  end
end

# Here's where the action starts
#
puts("autorun.rb: Running rover mission")
launch_it
watch_it
