# Set the instance id after calling 'cap instance:start'
set :instance_id, "i-rock"
# Set the instance url, which can be found by calling 'ec2-describe-instances'
# after the instance has booted
set :instance_url, "ec2-00-000-000-000.compute-1.amazonaws.com"

set :image_id, "ami-bded09d4"

role :app, instance_url
set :application, "example"

# Replace with your AWS credentials
set :keypair, "your-keypair"
set :account_id, "1234567890"
set :access_key_id, "1234567890ASDFG"
set :secret_access_key, "/asdfghj/sh1j4ksxss024011sfds"
set :pk, "pk-SLJSLK3411SADJAFASF0.pem"
set :cert, "cert-SLJSLK3411SADJAFASF0AFASF0.pem"

set :username, "root"
set :keypair_full_path, "#{ENV['HOME']}/.ec2/id_rsa-#{keypair}"

ssh_options[:username] = username
ssh_options[:keys] = keypair_full_path

namespace :instance do
desc "Start an instance"
task :start do
system "ec2-run-instances #{image_id} -k #{keypair}"
end

desc "Stop running instance"
task :stop do
system "ec2-terminate-instances #{instance_id}"
end

desc "SSH to running instance"
task :ssh do
system "ssh -i #{keypair_full_path} #{username}@#{instance_url}"
end

desc "Install and configure apache2 and passenger"
task :bootstrap do
run <<-CMD
apt-get install apache2 -y &&
apt-get install apache2-prefork-dev -y &&
gem install passenger --no-ri --no-rdoc &&
cd /usr/lib/ruby/gems/1.8/gems/passenger-2.0.3 &&
rake clean apache2 &&
echo "#phusion passenger" >> /etc/apache2/apache2.conf &&
echo "LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.0.3/ext/apache2/mod_passenger.so" >> /etc/apache2/apache2.conf &&
echo "PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.0.3" >> /etc/apache2/apache2.conf &&
echo "PassengerRuby /usr/bin/ruby1.8" >> apache2.conf &&
/etc/init.d/apache2 restart
CMD
end

desc "Serve an example merb app with passenger"
task :example_app do
run <<-CMD
echo "127.0.0.1 localhost #{instance_url}" >> /etc/hosts &&
gem i merb --no-ri --no-rdoc &&
gem i hpricot --no-ri --no-rdoc &&
cd /var/www &&
merb-gen app #{application} --flat &&
mkdir #{application}/public #{application}/tmp #{application}/log &&
echo "#{RACK_CONFIG}" >> #{application}/config.ru &&
echo "<VirtualHost *>" >> /etc/apache2/sites-available/#{application} &&
echo " ServerName #{instance_url}" >> /etc/apache2/sites-available/#{application} &&
echo " DocumentRoot /var/www/#{application}/public" >> /etc/apache2/sites-available/#{application} &&
echo " ErrorLog /var/www/#{application}/log/error.log" >> /etc/apache2/sites-available/#{application} &&
echo "</VirtualHost>" >> /etc/apache2/sites-available/#{application} &&
cd /etc/apache2/sites-available &&
a2ensite #{application} &&
/etc/init.d/apache2 restart
CMD
end
end

RACK_CONFIG = %{
require 'rubygems';
require 'merb-core';

Merb::Config.setup(:merb_root => '.', :environment => ENV['RACK_ENV']);
Merb.environment = Merb::Config[:environment];
Merb.root = Merb::Config[:merb_root];
Merb::BootLoader.run;
\n
run Merb::Rack::Application.new
}