namespace :rainbows do

set :rainbows_bin, fetch(:rainbows_bin, 'rainbows')

desc 'Start rainbows'
task :start do
  on roles :app do
    if !pid_exist?
      within release_path do
        execute :bundle, "exec #{fetch(:rainbows_bin)} -c config/#{fetch(:rainbows_bin)}.rb --listen 'unix://#{shared_path}/sockets/#{fetch(:rainbows_bin)}.sock' -E #{fetch(:stage)} -D"
        info 'Rainbows started.'
      end
    else
      info 'Rainbows is running, not need to start.'
    end
  end
end

desc 'Stop rainbows'
task :stop do
  on roles :app do
    pid_exist = pid_exist?
    times = 0
    until !pid_exist && times < 10 do
      within release_path do
        execute "kill -s QUIT `cat #{shared_path}/pids/#{fetch(:rainbows_bin)}.pid`;true"
      end
      sleep times + 1
      pid_exist = pid_exist?
      times = times + 1
    end

    if times >= 9
      within shared_path do
        execute :rm, 'pids/#{fetch(:rainbows_bin)}.pid;true'
      end
    end
  end
end

desc 'Restart rainbows'
task :restart do
  pid_exist = true
  on roles :app do
    pid_exist = pid_exist?
    if pid_exist
      within release_path do
        execute "kill -s USR2 `cat #{shared_path}/pids/#{fetch(:rainbows_bin)}.pid`;true"
      end
    end
  end
  invoke 'rainbows:start' unless pid_exist
end

desc 'Cold Restart rainbows'
task :cold_restart do
  invoke 'rainbows:stop'
  invoke 'rainbows:start'
end

def pid_exist?
  'true' ==  capture("if [ -e #{shared_path}/pids/#{fetch(:rainbows_bin)}.pid ]; then echo 'true'; fi").strip
end

before 'deploy:published', 'rainbows:restart'

end