#!/usr/bin/env ruby
require 'rubygems'
require 'fileutils'
require "thor"

class Marvin < Thor
  
  GEM_ROOT = File.expand_path(File.join(File.dirname(__FILE__), ".."))
  
  attr_accessor :dest
  
  # Map default help tasks.
  map ["-h", "-?", "--help", "-D"] => :help
  
  desc "create [PATH]", "creates a new marvin app at the given path"
  method_options :verbose => :boolean
  def create(path)
    @dest    = File.expand_path(path)
    @verbose = options[:verbose]
    if File.directory?(@dest)
      STDOUT.puts "The given directory, \"#{path}\", already exists."
      exit! 1
    else
      say "Creating Marvin app"
      say " => Making directories"
      mkdir   @dest
      mkdir   source(@dest, "script")
      mkdir   source(@dest, "config")
      mkdir   source(@dest, "handlers")
      mkdir_p source(@dest, "tmp/pids")
      mkdir   source(@dest, "log")
      mkdir   source(@dest, "lib")
      say " => Copying files..."
      copy "config/setup.rb"
      copy "config/connections.yml.sample", "config/connections.yml"
      copy "config/settings.yml.sample",    "config/settings.yml"
      copy "handlers/hello_world.rb"
      copy "handlers/debug_handler.rb"
      %w(client console distributed_client ring_server status).each do |c|
        copy "script/#{c}"
        FileUtils.chmod 0755, source(@dest, "script/#{c}")
      end
      say "Done!"
    end
  end
  
  desc "start [PATH]", "starts client at the given path"
  def start(path = ".")
    @dest = File.expand_path(path)
    if File.exist?(source(@dest, "script/client"))
      Dir.chdir(@dest) { exec "script/client" }
    else
      STDOUT.puts "Woops! #{@dest.gsub(" ", "\\ ")} doesn't look to be a marvin directory."
      exit!
    end
  end
  
  desc "status [PATH]", "shows status of marvin app at a given location"
  def status(path = ".")
    @dest = File.expand_path(path)
    if File.exist?(source(@dest, "script/status"))
      Dir.chdir(@dest) { exec "script/status" }
    else
      STDOUT.puts "Woops! #{@dest.gsub(" ", "\\ ")} doesn't look to be a marvin directory."
      exit!
    end
  end
  
  private
  
  def source(*args)
    File.expand_path(File.join(*args))
  end
  
  def copy(from, to = from)
    s, d = source(GEM_ROOT, from), source(@dest, to)
    say " --> cp #{s.gsub(" ", "\\ ")} #{d.gsub(" ", "\\ ")}" if @verbose
    FileUtils.cp_r(s, d)
  end
  
  def mkdir(path)
    say " --> mkdir #{path.gsub(" ", "\\ ")}" if @verbose
    FileUtils.mkdir path
  end
  
  def mkdir_p(path)
    say " --> mkdir #{path.gsub(" ", "\\ ")}" if @verbose
    FileUtils.mkdir_p path
  end
  
  def say(text)
    STDOUT.puts text
  end
  
end

# Check if we have arguments, we run the normal
# thor task otherwise we just print the help
# message.
if ARGV.empty?
  Marvin.new.help
else
  Marvin.start
end