#--
# $Id: remote.rake 179 2007-06-13 13:15:21Z aurelian $
#++

# remote host
$host = 'example.com'
# remote user
$user = 'aurelian'
# remote port
$port = 2582
# reomte path
$path = '/home/u8909192/www/example.com'

begin
  # assume rubygems loaded
  require 'ruby-growl'
  require 'net/ssh'
rescue LoadError => error # fail later
  puts "===> #{error}"
end

# {{{ remote_execute( session, command )
def remote_execute( session, command )
  growl = Growl.new "localhost", "ruby-growl", ["ruby-growl"]
  session.open_channel do | channel |
    channel.on_data do | ch, data |
      puts "#{session.host} ===> #{data}"
      growl.notify "ruby-growl", "Got data from #{session.host}", data[0].to_s
    end
    channel.on_close do | ch |
      puts "#{session.host} ===> channel closed."
      growl.notify "ruby-growl", "Channel Closed", "Channel with #{session.host} succesfully closed"
    end
    growl.notify "ruby-growl", "Command Sent", command
    puts "===> Executing #{command}"
    channel.exec "cd #{$path} && #{command}"
    # channel.close
  end
end
# }}}

# {{{ remote_session( command )
def remote_session( command )
  Net::SSH.start( $host, $user, :port => $port ) do | session |
    remote_execute session, command
    session.loop
  end
  rescue StandardError => error
    puts "===> Got #{error.class.name}: "
    puts "===> #{error}"
end
# }}}

namespace :remote do
  desc "Connect with ssh and list the top level project files (hello world)."
  task :connect do
    remote_session 'ls -la'
  end

  desc "Updates the code to the lastest revison (svn up -rENV['REV'])."
  task :update do
    rev = ENV['REV'].nil? ? 'HEAD' : ENV['REV']
    remote_session "svn up -r#{rev}" #rake remote:update REV=444
  end

  desc "Executes a rake command on the remote server"
  task :rake do
    cmd = ENV['CMD'].nil? ? '' : ENV['CMD'] #rake remote:rake CMD=db:migrate
    remote_session "rake #{cmd}"
  end

  namespace :mongrel do
    desc "Stops the mongrel cluster"
    task :stop do
      remote_session "mongrel_rails cluster::stop"
    end

    desc "Starts the mongrel cluster"
    task :start do
      remote_session "mongrel_rails cluster::start"
    end

    desc "Restarts the server"
    task :restart => [:stop, :start] do
    end

  end  # /mongrel

end # /remote