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_versions
  ubiquo_guides
  ubiquo_design
]

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

# File railties/lib/rails_generator/generators/applications/app/template_runner.rb, line 69
def plugin(name, options)
  log 'plugin', name

  if options[:git] && options[:submodule]
    in_root do
      branch = "-b #{options[:branch]}" if options[:branch]
      Git.run("submodule add #{branch} #{options[:git]} vendor/plugins/#{name}")
    end
  elsif options[:git] || options[:svn]
    in_root do
      run_ruby_script("script/plugin install #{options[:svn] || options[:git]}", false)
    end
  else
    log "! no git or svn provided for #{name}.  skipping..."
  end
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
# To ask needed settings when boostraping the app
appname             = "<%= @opts[:app_name] %>"
exception_recipient = "<%= @opts[:exception_recipient] %>"
sender_address      = "<%= @opts[:sender_address] %>"
# Remove rails temporary directories
["./tmp/pids", "./tmp/sessions", "./tmp/sockets", "./tmp/cache"].each do |f|
  run("rmdir ./#{f}")
end
# Hold empty dirs by adding .gitignore to each (to avoid git missing needed empty dirs)
run("find . \\( -type d -empty \\) -and \\( -not -regex ./\\.git.* \\) -exec touch {}/.gitignore \\;")

# git:rails:new_app
git :init

# Add default files to ignore (for Rails) to git
file '.gitignore', <<-CODE
log/\*.log
log/\*.pid
db/\*.db
db/\*.sqlite3
db/schema.rb
tmp/\*\*/\*
.DS_Store
doc/api
doc/app
config/database.yml
CODE
initializer 'ubiquo_config.rb', <<-CODE
Ubiquo::Config.add do |config|
  config.app_name = "#{appname}"
  config.app_title = "#{appname.gsub(/_/, " ").capitalize}"
  config.app_description = "#{appname.gsub(/_/, " ").capitalize}"
  case RAILS_ENV
  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
<% if @opts[:template] == :edge %>
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
<% end %>
# 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
ExceptionNotifier.exception_recipients = %w( #{exception_recipient} )
ExceptionNotifier.sender_address = %("Application Error" <#{sender_address}>)
ExceptionNotifier.email_prefix = "[#{appname} \#\{RAILS_ENV\} ERROR]"
CODE
# Initializer for session
# Needs 1 param:
#   appname -> Application Name (Ex: test)
initializer 'session_store.rb', <<-CODE
ActionController::Base.session = {
  :key         => "_ubiquo_#{appname}_session",
  :secret      => '#{(1..40).map { |x| (65 + rand(26)).chr }.join}'
}
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
# gnuine routes.rb
ubiquo_routes = selected_plugins.map do |plugin|
  "  map.from_plugin :#{plugin}"
end.join("\n")
file 'config/routes.rb', <<-CODE
ActionController::Routing::Routes.draw do |map|

  map.namespace :ubiquo do |ubiquo|
  end

  # Ubiquo plugins routes. See routes.rb from each plugin path.
<% if @opts[:template] == :edge && @opts[:profile] == :complete %>
  <%= "map.from_plugin :ubiquo_categories" %>
<% end %>
#{ubiquo_routes}

  ############# default routes
  #map.connect ':controller/:action/:id'
  #map.connect ':controller/:action/:id.:format'
end
CODE
# default rails environment.rb
file 'config/environment.rb', <<-CODE
# Be sure to restart your server when you modify this file

# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '<%= @opts[:rails] %>' unless defined? RAILS_GEM_VERSION

# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')

Rails::Initializer.run do |config|
  # Settings in config/environments/* take precedence over those specified here.
  # Application configuration should go into files in config/initializers
  # -- all .rb files in that directory are automatically loaded.

  # Add additional load paths for your own custom dirs

  # Specify gems that this application depends on.
  # They can then be installed with "rake gems:install" on new installations.
  # config.gem "bj"
  # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
  # config.gem "aws-s3", :lib => "aws/s3"
  # config.gem "rmagick", :lib => 'RMagick'

  # Only load the plugins named here, in the order given (default is alphabetical).
  # :all can be used as a placeholder for all plugins not explicitly named
  config.plugins = [ :ubiquo_core, :all ]

  # Skip frameworks you're not going to use. To use Rails without a database
  # you must remove the Active Record framework.
  # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]

  # Activate observers that should always be running
  # config.active_record.observers = :cacher, :garbage_collector, :forum_observer

  # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
  # Run "rake -D time" for a list of tasks for finding time zone names.
  config.time_zone = 'UTC'

# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
  # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
  # config.i18n.default_locale = :de
  config.i18n.load_path += Dir.glob(File.join("config", "locales", "**","*.{rb,yml}"))
  config.i18n.default_locale = :<%= @opts[:locale] %>
end
CODE
ubiquo_branch = <%= @opts[:template] == :edge ? 'nil' : "'0.7-stable'" %>
add_plugins(selected_plugins + external_plugins, :branch => ubiquo_branch, :devel => <%= @opts[:devel] ? true : false %>)

<% if @opts[:template] == :edge && @opts[:profile] == :complete %>
  add_plugins(['ubiquo_categories'], :branch => nil, :devel => <%= @opts[:devel] ? true : false %>)
<% end %>

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

# Bundler setup
gsub_file 'config/boot.rb', /Rails\.boot!/ do <<-CODE
class Rails::Boot
  def run
    load_initializer

    Rails::Initializer.class_eval do
      def load_gems
        @bundler_loaded ||= Bundler.require :default, Rails.env
      end
    end

    Rails::Initializer.run(:set_load_path)
  end
end

Rails.boot!
CODE
end
file 'config/preinitializer.rb', <<-CODE
begin
  require "rubygems"
  require "bundler"
rescue LoadError
  raise "Could not load the bundler gem. Install it with `gem install bundler`."
end

if Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24")
  raise RuntimeError, "Your bundler version is too old for Rails 2.3." +
   "Run `gem install bundler` to upgrade."
end

begin
  # Set up load paths for all bundled gems
  ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)
  Bundler.setup
rescue Bundler::GemNotFound
  raise RuntimeError, "Bundler couldn't find some gems." +
    "Did you run `bundle install`?"
end
CODE
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
file 'Gemfile', <<-CODE
source "http://rubygems.org"

gem "rails",     "= 2.3.11"
gem "lockfile",  ">= 1.4.3"
gem "i18n",      "< 0.5.0"

platforms :mri_18 do
  gem "#{adapter_gem}"
<% if @opts[:template] == :stable %>
  gem "daemons", "~> 1.1.2"
<% end %>
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 "ruby-debug"
  gem "ya2yaml", ">= 0.2.6"
  gem "highline", ">= 1.5.2"
  gem "ffi-ncurses", "~> 0.3.3", :platforms => :jruby
end

group :test do
  gem "mocha", ">= 0.9.8", :require => false
end
CODE
# we  need to take care of Jruby
<% if RUBY_PLATFORM =~ /java/ %>
run "jruby -S bundle install"
<% else %>
run "bundle install"
<% end %>
# End of bundler setup

<% 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 %>