namespace :napkin do

include Capistrano::Napkin::Utilities

task :verify_up_to_date do
  if using_git?
    set :local_branch, `git branch --no-color 2> /dev/null | sed -e '/^[^*]/d'`.gsub(/\* /, '').chomp
    set :local_sha, `git log --pretty=format:%H HEAD -1`.chomp
    set :origin_sha, `git log --pretty=format:%H #{fetch(:local_branch)} -1`
    unless fetch(:local_sha) == fetch(:origin_sha)
      abort """
      Your #{fetch(:local_branch)} branch is not up to date with origin/#{fetch(:local_branch)}.
      Please make sure you have pulled and pushed all code before deploying:

          git pull origin #{fetch(:local_branch)}
          # run tests, etc
          git push origin #{fetch(:local_branch)}

          """
    end
  end
end

task :calculate_tag do
  if using_git?
    # make sure we have any other deployment tags that have been pushed by others so our auto-increment code doesn't create conflicting tags
    `git fetch`
    if fetch(:stage) == :production
        invoke 'napkin:tag_production'
    else
        invoke 'napkin:tag_staging'
    end

      system "git push --tags origin #{fetch(:local_branch)}"
      if $? != 0
        abort "git push failed"
      end

  end
end

task :configuration do
  puts "Gitflow"
  Napkin::Configuration.ablerc.stub.generate :local
  exit
end

task :tag_staging do
  staging_destination = deploy_from

  set :branch, staging_destination
end

desc "Show available releases"
task :releases do
  available_releases
end

desc "Push the approved tag to production. Pass in tag to deploy with '-s tag=staging-YYYY-MM-DD-X-feature'."
task :tag_production do

   production_destination = deploy_from

   set :really_deploy, ask("Do you really want to deploy #{production_destination}?", "N")

   exit(1) unless fetch(:really_deploy) =~ /^[Yy]$/

   set :branch, production_destination
end

end

namespace :deploy do

namespace :pending do
  task :compare do
    #gitflow.commit_log
  end
end

end