#! /usr/bin/env ruby

require 'optparse'
require 'rock/bundle'

Rock::Bundles.setup_search_paths
filename =
    if File.file?(ARGV.first)
        ARGV.shift
    elsif file = Rock::Bundles.find_file('scripts', ARGV.first, :order => :specific_first)
        ARGV.shift
        file
    elsif file = Rock::Bundles.find_file('scripts', "#{ARGV.first}.rb", :order => :specific_first)
        ARGV.shift
        file
    end

if filename
    if Rock::Bundles.is_ruby_script?(filename)
        load filename
        exit
    else
        exec(filename, *ARGV)
    end
end

do_start = false
do_log = false

require 'orocos'
require 'orocos/scripts'
require 'orocos/async'
Rock::Bundles.initialize

parser = OptionParser.new
Orocos::Scripts.common_optparse_setup(parser)
parser.banner = "rock-run [--gui] task_model task_name"
parser.on '--start', 'starts the task' do
    do_start = true
end
parser.on '--log', 'activate logging' do
    do_log = true
end

model, name = parser.parse(ARGV)

if Orocos::Scripts.gui?
    require 'vizkit'
end

if !name
    if model =~ /::/
        name = model.gsub(/::.*/, '')
        if Orocos.name_service.task_reachable?(name)
            name = "#{name}%i"
            100.times do |i|
                candidate = name % [i]
                if !Orocos.name_service.task_reachable?(candidate)
                    name = candidate
                    break
                end
            end
        end
    else
        name = '' # No prefix
    end
end

Orocos::Scripts.run model => name do |*processes|
    if do_log
        Orocos.log_all
    end

    tasks = processes.map do |p|
        p.each_task.to_a
    end.flatten.find_all { |t| t.model.name != "logger::Logger" }

    tasks.each do |t|
        Orocos::Scripts.conf(t)
    end

    if Orocos::Scripts.gui?
        tasks.each do |t|
            Vizkit.display t.to_proxy
        end
    end

    if do_start
        tasks.each do |t|
            t.configure if t.rtt_state == :PRE_OPERATIONAL
            t.start
        end
    end

    if Orocos::Scripts.gui?
        Vizkit.exec
    else
        Orocos.watch(*tasks)
    end
end

