#!/usr/bin/ruby
require "include/program.rb"

NAO_BUILD_CONFIG = "Optimized"

COLTABLE_USAGE =
<<eos
usage: (Linux only)
  1. ./coltable current         a + b
    a. ./coltable up              svn up for working copy
    b. ./coltable build           builds Nao with Optimized config
  3. ./coltable create <ip>     a + b + c
    a. ./coltable copy <ip>       deploys compiled Nao on 192.168.X.<ip> or <ip>
    b. ./coltable connect <ip>    connects to 192.168.X.<ip> via ssh or <ip>
    c. ./coltable sim <ip>        starts simulator and conects to 192.168.X.<ip> or <ip>
  4. wait...
  5. ./coltable deploy          deploys camera calibrations and color tables on all Naos
  6. ./coltable restart_all     restarts bhumand on all Naos
  or
  6. ./coltable ci              commits the color table
eos

def ip_convert ip_raw
    if ip_raw[/\d+\.\d+\.\d+\.\d+/]
      ip_raw
    else
      WLAN_IP_PREFIX.to_s + ip_raw
    end
end

class Program
  def print_usage
    puts COLTABLE_USAGE
  end

  def current
    up
    dir "Make/"
    build
  end

  def up
    dir BASE_DIR
    execute "svn up", "Updating"
  end

  def build flags = BUILD_FLAGS, rebuild = false
    dir MAKE_DIR
    execute "make clean", "Cleaning" if rebuild
    execute "make Nao CONFIG=#{NAO_BUILD_CONFIG} #{flags}", "Building Nao"
  end

  def create ip_raw, flags = BUILD_FLAGS
    ip = ip_convert ip_raw
    copy ip
    connect ip
    sim ip, flags
  end

  def copy ip_raw
    ip = ip_convert ip_raw
    dir MAKE_DIR
    execute "make copyfiles", "Building Copyfiles"
    execute "./copyfiles #{NAO_BUILD_CONFIG} #{ip}", "Copyfiles"
  end

  def connect ip_raw
    ip = ip_convert ip_raw
    dir MAKE_DIR
    execute "ssh #{USER}@#{ip} -i #{KEY}", "Connecting to #{ip}"
  end

  def sim ip_raw, flags = BUILD_FLAGS
    ip = ip_convert ip_raw
    dir MAKE_DIR
    execute "make Simulator #{flags}", "Building Simulator"
    execute "echo \"sc Remote #{ip}\" > #{SCENES_DIR}connect.con", "Writing connect.con"
    execute "#{BUILD_DIR}Simulator/Linux/DebugWithReleaseLibs/Simulator #{SCENES_DIR}RemoteRobot.ros", "Starting Simulator"
  end

  def deploy
    execute "./colorDeploy.sh", "Deploying color table"
  end

  def restart_all
    execute "./bhuman_restart", "Restarting bhumand on all robots"
  end

  def rebuild flags = BUILD_FLAGS
    build flags, true
  end

  def ci
    dir CONFIG_DIR
    execute "svn ci Locations/Default/coltable.c64 -m \"color table\"", "Commiting color table..."
  end

  def ping ip_raw, count = 10
    ip = ip_convert ip_raw
    execute "ping -c#{count} #{ip}", "Ping #{IPS[ip] ? IPS[ip] : CIPS[ip]}"
  end
end

Program.name "coltable"
Program.debug true

Program.execute
