external_plugins = %w[
  calendar_date_select
  exception_notification
  responds_to_parent
  tiny_mce
  paperclip
]
minimal_plugins = %w[ ubiquo_core ubiquo_authentication ubiquo_access_control ubiquo_scaffold ]
rest_plugins = %w[
  ubiquo_media
  ubiquo_jobs
  ubiquo_i18n
  ubiquo_activity
  ubiquo_categories
  ubiquo_versions
  ubiquo_guides
  ubiquo_design
  translate
]

choosen_plugin_set = "<%= @opts[:profile].to_s %>"

case choosen_plugin_set
  when "minimal" then selected_plugins = minimal_plugins
  when "custom"
    selected_plugins = (minimal_plugins + <%= @opts[:plugins].inspect %>).uniq
  else selected_plugins = minimal_plugins + rest_plugins
end

# temporally overriden to the gemified set of plugins
selected_plugins = %w[ubiquo_core ubiquo_authentication ubiquo_access_control]

# File railties/lib/rails/generators/rails/app/app_generator.rb, line 238
def file(*args, &block)
  config = args.last.is_a?(Hash) ? args.pop : {}
  # Force overwrite of existent files
  create_file(*args, {:force => true}.merge(config), &block)
end

# File 'railties/lib/rails/generators/actions.rb', line 227
def rake(command, options={})
  log :rake, command
  env  = options[:env] || 'development'
  sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
  rvm = "<%= @opts[:rvm] ? "rvm @#{@opts[:app_name]} do " : '' %>"
  in_root { run("#{sudo}#{rvm}#{extify(:rake)} #{command} RAILS_ENV=#{env}", :verbose => false) }
end

def add_plugins(plugin_names, options={})
  git_root = options[:devel] ? 'git@github.com:gnuine' : 'git://github.com/gnuine'
  plugin_names.each { |name| plugin name, :git => "#{git_root}/#{name}.git", :branch => options[:branch], :submodule => true }
end

def plugin_repo(name, options={})
  git_root = options[:devel] ? 'git@github.com:gnuine' : 'git://github.com/gnuine'
  "#{git_root}/#{name}.git"
end

# To ask needed settings when boostraping the app
appname             = "<%= @opts[:app_name] %>"
exception_recipient = "<%= @opts[:exception_recipient] %>"
sender_address      = "<%= @opts[:sender_address] %>"
# Hold empty dirs by adding .gitkeep to each (to avoid git missing needed empty dirs)
run("find . \\( -type d -empty \\) -and \\( -not -regex ./\\.git.* \\) -exec touch {}/.gitkeep \\;")

# git:rails:new_app
git :init

# Add default files to ignore (for Rails) to git
file '.gitignore', <<-CODE
# See http://help.github.com/ignore-files/ for more about ignoring files.

# Ignore bundler config
.bundle

log/\*.log
log/\*.pid
db/\*.db
db/\*.sqlite3
db/schema.rb
/tmp
/nbproject
.rvmrc
.DS_Store
doc/api
doc/app
CODE
initializer 'ubiquo_config.rb', <<-CODE
Ubiquo::Settings.set do |config|
  config.app_name = "#{appname}"
  config.app_title = "#{appname.gsub(/_/, " ").capitalize}"
  config.app_description = "#{appname.gsub(/_/, " ").capitalize}"
  case Rails.env.to_s
  when 'development', 'test'
    config.notifier_email_from = 'railsmail@gnuine.com'
  else
    config.notifier_email_from = 'railsmail@gnuine.com'
  end
end
CODE

# Initializer for ubiquo crontab
initializer 'ubiquo_crontab.rb', <<-CODE
# -*- coding: utf-8 -*-
Ubiquo::Cron::Crontab.schedule do |cron|
  # Who to mail on errors
  # cron.mailto = 'errors@change.me'

  # *     *     *   *    *
  # -     -     -   -    -
  # |     |     |   |    |
  # |     |     |   |    +----- day of week (0 - 6) (Sunday=0)
  # |     |     |   +------- month (1 - 12)
  # |     |     +--------- day of        month (1 - 31)
  # |     +----------- hour (0 - 23)
  # +------------- min (0 - 59)

  # Examples:
  # "30 08 10 06 *"  Executes on 10th June 08:30 AM.
  # "00 11,16 * * *" Executes at 11:00 and 16:00 on every day.
  # "00 09-18 * * *" Executes everyday (including weekends) during the working hours 9 a.m – 6 p.m
  # "* * * * *"      Execute every minute.
  # "*/10 * * * *"   Execute every 10 minutes.
  # "@hourly"        Execute every hour.
  # "@daily"         Execute daily.
  # "@monthly"       Execute monthly.
  # "@reboot"        Execute after every reboot.

  # The specification of days can be made in two fields: month day and weekday.
  # If both are specified in an entry, they are cumulative meaning both of the entries will get executed.

  # See man 5 crontab for more information.

  # Executes the routes (rake) task every minute
  # cron.rake   "* * * * *", "routes"

  # Executes the routes (rake) task every minute and logs debug information
  # cron.rake   "* * * * *", "routes debug='true'"

  # Executes a script/runner like task
  # cron.runner "* * * * *", "puts 6+6"
end
CODE
# Initializer for exception notifier
# Needs 3 params:
#   appname -> Application name (Ex: test)
#   exception_recipient -> email to deliver application error messages (Ex: developers@foo.com)
#   sender_adress -> email to user in from when delivering error message (Ex: notifier@foo.com)
initializer 'exception_notifier.rb', <<-CODE
# Exception notification
#{appname.camelize}::Application.config.middleware.use ExceptionNotifier,
  :email_prefix => "[#{appname} \#\{Rails.env\} ERROR]",
  :sender_address => %("Application Error" <#{sender_address}>),
  :exception_recipients => %w( #{exception_recipient} )
CODE
postgresql =  <<-CODE
base_config: &base_config
    encoding: unicode
    adapter:  postgresql
    host: localhost
    username: #{%x{id -u -n}.strip}
    password:

development:
  <<: *base_config
  database: #{appname}_development

test:
  <<: *base_config
  database: #{appname}_test

preproduction:
  <<: *base_config
  database: #{appname}_preproduction

production:
  <<: *base_config
  database: #{appname}_production
CODE

mysql = <<-CODE
base_config: &base_config
  encoding: utf8
  adapter:  mysql
  pool: 5
  username: root
  password:
  socket: /var/run/mysqld/mysqld.sock

development:
  <<: *base_config
  database: #{appname}_development

test:
  <<: *base_config
  database: #{appname}_test

preproduction:
  <<: *base_config
  database: #{appname}_preproduction

production:
  <<: *base_config
  database: #{appname}_production
CODE

sqlite3 = <<-CODE
base_config: &base_config
  encoding: unicode
  adapter:  sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *base_config
  database: db/#{appname}_development.db

test:
  <<: *base_config
  database: db/#{appname}_test.db

preproduction:
  <<: *base_config
  database: db/#{appname}_preproduction.db

production:
  <<: *base_config
  database: db/#{appname}_production.db
CODE
choosen_adapter = "<%= @opts[:database] %>"
case choosen_adapter
  when "mysql" then file 'config/database.yml', mysql
  when "sqlite" then file 'config/database.yml', sqlite3
  else file 'config/database.yml', postgresql
end
file 'config/routes.rb', <<-CODE
#{appname.camelize}::Application.routes.draw do
  mount Ubiquo::Engine => '/ubiquo'

#  map.namespace :ubiquo do |ubiquo|
#  end

#  Translate::Routes.translation_ui(map) unless Rails.env.production?
end
CODE
# default rails environment.rb
ubiquo_branch = <%= @opts[:template] == :edge ? 'nil' : "'0.8-stable'" %>
#add_plugins(selected_plugins + external_plugins, :branch => ubiquo_branch, :devel => <%= @opts[:devel] ? true : false %>)
<% if @opts[:clone_gems] %>
  (selected_plugins).each do |plugin_name|
    run "git clone #{plugin_repo(plugin_name)} <%= @opts[:gem_path] %>/#{plugin_name}"
  end
<% end %>

adapter_gem = case choosen_adapter
  when "mysql" then "mysql"
  when "sqlite" then "sqlite3"
  else "pg"
end
jruby_adapter_gem = adapter_gem == "pg" ? "postgres" : adapter_gem

ubiquo_gems = (selected_plugins).map do |plugin|
  <% if @opts[:gem_path] %>
    "  gem \"#{plugin}\""
  <% else %>>
    "  gem \"#{plugin}\", :git => #{plugin_repo(plugin)}"
  <% end %>
end.join("\n")

file 'Gemfile', <<-CODE
source "https://rubygems.org"

gem "rails",     "~> 3.2.0.rc2"

platforms :mri_19 do
  gem "#{adapter_gem}"
end

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.0'

  gem 'uglifier', '>= 1.0.3'
end

gem 'linecache19', :git => 'git://github.com/mark-moseley/linecache'
gem 'ruby-debug-base19x', '~> 0.11.30.pre4'
gem 'ruby-debug19'

gem 'jquery-rails'

group :test do
  gem "mocha", ">= 0.9.8", :require => false
end

<% if @opts[:gem_path] %>
path "<%= @opts[:gem_path] %>" do
#{ubiquo_gems}
end
<% else %>
#{ubiquo_gems}
<% end %>

gem "paperclip", "~> 2.4.5"
gem "exception_notifier", "~> 1.0.0"

<% if @opts[:profile] == :complete # used in i18n %>
#gem 'routing-filter', '~> 0.2.4', :require => false
<% end %>

platforms :jruby do
  #gem "activerecord-jdbc-adapter", "~> 1.1.1"
  #gem "jdbc-#{jruby_adapter_gem}"
  #gem "jruby-openssl", "~> 0.7.3"
end

group :development do
  #gem "ya2yaml", ">= 0.2.6"
  #gem "highline", ">= 1.5.2"
  #gem "ffi-ncurses", "~> 0.3.3", :platforms => :jruby
end
CODE

<% if @opts[:rvm] %>
run "rvm gemset create #{appname}"
file '.rvmrc', <<-CODE
rvm gemset use #{appname}
CODE
run "rvm @#{appname} do gem install bundler --no-ri --no-rdoc"
<% end %>

# we  need to take care of Jruby
bundle_command = "<%= @opts[:rvm] ? 'rvm @#{appname} do ' : '' %> bundle install"
<% if RUBY_PLATFORM =~ /java/ %>
run "jruby -S #{bundle_command}"
<% else %>
run" #{bundle_command}"
<% end %>
# End of bundler setup

rake("calendardateselect:install")
rake("ubiquo:install OVERWRITE=yes")

<% if RUBY_PLATFORM =~ /java/ %>
  generate(:jdbc)
<% end %>

<% if @opts[:gnuine] %>
   rake("db:create:all")
rake("ubiquo:db:reset")
<% end %>

git :add => "."
git :commit => "-a -m 'Initial #{appname} commit'"

<% unless @opts[:gnuine] %>
puts "Run script/server and go to http://localhost:3000/ and follow the instructions there."
<% end %>