# require "bundler/capistrano"

set :stages,                %w(staging production)
set :default_stage,         "staging"

require 'yaml'
require 'capistrano/ext/multistage'

default_run_options[:pty] = true

set :application,           "map_platform"
set :domain,                "www.hamburg-global.de"
set :url,                   "http://www.hamburg-global.de/"
set :default_env,           "staging"

set :pm_url,                "https://www.rekoder.de/pm/"

set :repository,            "ssh://ulf_t@rekoder.de:4242/var/repos/map-platform.git"
set :scm,                   :git
set :deploy_via,            :remote_cache
set :keep_releases,         5
set :user,                  "deploy"

set :runner,                nil
set :use_sudo,              false
set :scm_verbose,           true

set :ssh_options,           :port => '4242'
set :ssh_options,           :forward_agent => true
set :ssh_options,           :verbose => :debug
# set :ssh_options,           :keys => %w(c:/Users/ulf_t/.ssh/ut_ant_key.ppk.openssh)
# set :ssh_options,           :keys => %w(i:/Users/ulf_t/.ssh/ut_ant_key.ppk.openssh)


#### roles ##################################################
role :web,                  "#{domain}"
role :app,                  "#{domain}"
role :db,                   "#{domain}", :primary => true


require File.expand_path("../deploy/notifier", __FILE__)
set :notify_emails, ["ulf.treger@3plusx.de","anke.schwarzer@ewnw.de","info@ewnw.de","hallo@ankeschwarzer.com"]
# set :notify_emails, ["ulf.treger@3plusx.de"]

before  'deploy:symlink_shared',      'setup:shared_directories'
before  'deploy:notify',              'deploy:revisions'
after   'deploy',                     'deploy:notify'


namespace :setup do
  desc "Create file directories"
  task :shared_directories do
    run "mkdir -p #{shared_path}/uploads"
  end
end

namespace :deploy do
  task :start do ; end
  task :stop do ; end
  task :restart, :roles => :app, :except => { :no_release => true } do
    run "#{try_sudo} mkdir #{File.join(current_path,'rails/map_plattform/tmp')}"
    run "#{try_sudo} touch #{File.join(current_path,'rails/map_plattform/tmp','restart.txt')}"
  end


  desc "Symlink shared directories"
  task :symlink_shared do
    run "ln -nfs #{shared_path}/uploads #{release_path}/rails/map_plattform/public/uploads"
    # ln -nfs /srv/rails-apps/map_platform/staging_app/shared/uploads /srv/rails-apps/map_platform/staging_app/current/rails/map_plattform/public/uploads
  end


#   desc "Backup the remote production database"
#   task :db_backup, :roles => :db, :only => { :primary => true } do
#     filename = "#{application}.dump.#{Time.now.to_i}.sql.bz2"
#     file = "/var/rails-apps/dumps/#{filename}"
#     db = YAML::load(ERB.new(IO.read(File.join(File.dirname(__FILE__), 'database.yml'))).result)["#{stage}"]
#     run "mysqldump -u #{db['username']} --password=#{db['password']} #{db['database']} | bzip2 -c > #{file}"  do |ch, stream, data|
#       puts data
#     end
#   end

  after "deploy:update_code", :roles => [:web] do
    #set version
    run "echo \"#{real_revision[0,7]} vom #{Time.now.strftime("%d.%m.%Y")} #{Time.now.strftime("%H:%M:%S")}\" > #{release_path}/rails/map_plattform/app/views/shared/_version.haml"
    # set symlink to images
    run "ln -nfs #{shared_path}/uploads #{release_path}/rails/map_plattform/public/uploads"
  end


  # desc "Backup the database before running migrations"
  # before "deploy:migrate" do
    # db_backup
  # end


  # for testing
  desc "Send email notification"
  task :notify do
    Notifier.deploy_notification(self).deliver
  end

  desc "Show currently deployed revision on server."
  task :revisions, :roles => :app do
    current, previous, latest = current_revision[0,7], previous_revision[0,7], real_revision[0,7]
    git_log = "Deployed Revision: #{current}\n"
    git_log += "      Previous Revision: #{previous}\n"

    # If deployed and master are the same, show the difference between the last 2 deployments
    base_label, new_label, base_rev, new_rev = latest != current ? \
         ["deployed", "master", current, latest] : \
         ["previous", "deployed", previous, current]

    # Show difference between master and deployed revisions
    if (diff = `git log #{base_rev}..#{new_rev} --oneline`) != ""
      diff.gsub!(/^([a-f0-9]+) /, "\\1: ")
      diff = "        " << diff.gsub("\n", "\n        ") << "\n"
      # Indent commit messages nicely, max 80 chars per line, line has to end with space.
      diff = diff.split("\n").map{|l|l.scan(/.{1,120}/).join("\n"<<" "*14).gsub(/([^ ]*)\n {14}/m,"\n"<<" "*14<<"\\1")}.join("\n")
      git_log += "\n      Commits since last deployment:\n\n"
      git_log += diff
    end

    set :git_log, git_log
    puts git_log
  end

end
