begin
  require 'vlad'
  Vlad.load :app => :passenger
rescue LoadError
  # do nothing
  raise "vlad didn't load!"
end

require 'renfield'

namespace :vlad do

  @staging_server = "rails_staging"
  @production_server = "rails_ohwr"

  desc "Sets user staging server"
  task :staging do
    info "Setting up staging environment"
    set :domain, @staging_server
    set :rails_env, 'staging'
  end
  
  desc "Sets production server"
  task :production do
    info "Setting up production environment"
    set :domain, @production_server
  end

  namespace :production do
    desc "Updates production with the latest version"
    remote_task :update => %w[vlad:production vlad:confirm vlad:ohwr:update]
  end

  namespace :staging do
    desc "Clones production db and files into staging"
    remote_task :clone_production => %w[
      vlad:staging
      vlad:ohwr:dump
      vlad:staging:clone_db
      vlad:staging:clone_files
      vlad:restart
    ]

    desc 'Clone DB from production to user staging'
    remote_task :clone_db => ['vlad:staging'] do
      info "Clonning DB from production to staging"
      run "pg_dump -c -h #{@production_server} -U ohwr ohwr | psql -h localhost -U ohwr ohwr"
    end

    desc "Makes a clone of the production files directory on staging"
    remote_task :clone_files => ['vlad:staging'] do
      info "Cloning production files into staging"
      files_path = "#{shared_path}/files"
      run "rm -rf #{files_path}"
      run "mkdir -p #{files_path}"
      run "rsync -r #{@production_server}:/#{files_path} #{files_path}"
    end

    desc "Updates staging with the latest version"
    remote_task :update => %w[vlad:staging vlad:ohwr:update]
  end

  namespace :ohwr do

    desc "update server" # code, files, config_files, db_migrate, clean_up
    task :update => %w[
      vlad:maintenance:set
      vlad:ohwr:dump
      vlad:update
      vlad:ohwr:symlinks
      vlad:ohwr:session_store
      vlad:chown
      vlad:ohwr:migrate
      vlad:ohwr:cleanup
      vlad:restart
      vlad:maintenance:remove
      vlad:cleanup
    ]

    desc "executes rake config/initializers/session_store.rb"
    remote_task :session_store do
      info "Executing rake config/initializers/session_store.rb"
      remote_rake 'config/initializers/session_store.rb'
    end
    
    desc "Executing migrations of database and plugins"
    remote_task :migrate do
      info "Executing rake db:migrate_plugins db:migrate"
      #remote_rake 'db:migrate:upgrade_plugin_migrations db:migrate_plugins db:migrate'
      remote_rake 'db:migrate_plugins db:migrate'
    end

    desc "Clears redmine sessions and cache"
    remote_task :cleanup do
      info "Redmine clean up"
      remote_rake('tmp:cache:clear tmp:sessions:clear')
    end
    
    desc "Creates symlinks for all 'shared' files & folders"
    remote_task :symlinks do
      info "Creating symlinks"
      run "ln -s #{shared_path}/config/database.yml #{current_path}/config/database.yml"
      run "ln -s #{shared_path}/config/email.yml #{current_path}/config/email.yml"
      run "ln -s #{shared_path}/files #{current_path}/files"
    end

    desc "makes a security copy of the db and files folder on the dump folder"
    remote_task :dump => %w[ vlad:ohwr:dump:db vlad:ohwr:dump:files  vlad:ohwr:dump:cleanup ]

    #namespace redmine:dump
    namespace :dump do
      desc "dump redmine database"
      remote_task :db do
        info "Dumping the database"
        run "pg_dump -c -U ohwr ohwr | gzip > #{File.join(dump_path, 'ohwr.sql.gz')}"
      end

      desc "compressed copy of files folder into the dump folder"
      remote_task :files do
        info "Dumping the files folder"
        run "tar -czf #{dump_path}/files.tgz #{shared_path}/files/"
      end
      
      desc "removes older releases from the dump folder"
      remote_task :cleanup do
        info "Cleaning up dump folder"
        max = keep_releases
        if dump_releases.length <= max then
          puts "no old dump releases to clean up #{dump_releases.length} <= #{max}"
        else
          puts "keeping #{max} of #{dump_releases.length} dump releases"
     
          directories = (dump_releases - dump_releases.last(max)).map { |release|
            File.join(dumps_path, release)
          }.join(" ")
     
          run "rm -rf #{directories}"
        end
      end
    end # namespace :dump
  end # namespace :ohwr

  @dump_releases=nil
  def dump_releases
    if @dump_releases.nil?
      @dump_releases=run("ls -x #{dumps_path}").split.sort
    end
    return @dump_releases
  end

  def dumps_path
    return File.join(shared_path, 'dumps')
  end

  @dump_path=nil
  def dump_path
    if @dump_path.nil?
      @dump_path = File.join(dumps_path, now)
      run "mkdir -p #{@dump_path}"
    end
    return @dump_path
  end

end
