namespace :cul do

desc "Add tag based on current version from VERSION file"
task :auto_tag do
  current_version = "v#{IO.read("VERSION").strip}"

  ask(:tag, current_version)
  tag = fetch(:tag)

  system("git tag -a #{tag} -m 'auto-tagged' && git push origin --tags")
end

desc "Deploy downtime branch"
task :downtime do
  on roles(:web) do
    downtime_path = deploy_path.join("downtime")
    execute :rm, "-rf", downtime_path if test "[ -d #{downtime_path} ]"
    execute :mkdir, "-p", downtime_path

    within repo_path do
      execute :git, :archive, 'downtime', "| #{SSHKit.config.command_map[:tar]} -x -f - -C", downtime_path
    end

    tmp_current_path = releases_path.join(current_path.basename)
    execute :ln, "-s", downtime_path, tmp_current_path
    execute :mv, tmp_current_path, current_path.parent
  end
end

# Throws an error if any of the given variables are nil or blank, potentially prompting
# the user for a value if a variable was configured to be set by the ask() method.
def self.require_cap_variables!(variables)
  variables.each do |variable|
    value = fetch(variable) # fetch the variable, potentially prompting the use to enter a value on the command line
    next if value.is_a?(TrueClass) || value.is_a?(FalseClass)
    raise Capistrano::ValidationError, "Missing required variable #{variable}" if value.nil? || value.empty?
  end
end

def self.enter_y_to_continue(prompt)
  puts prompt
  set :confirmation_value, ask('"y" or "yes" to continue (or any other value to cancel)')
  entered_y = ['y', 'yes'].include?(fetch(:confirmation_value))
  delete :confirmation_value
  entered_y
end

def self.color_text(message, color_number=35)
  text_color = "\e[#{color_number}m"
  default_color = "\e[0m"
  text_color + message + default_color
end

end