require 'puppetlabs_spec_helper/rake_tasks'
require 'puppet-syntax/tasks/puppet-syntax'
require 'puppet_blacksmith/rake_tasks' if Bundler.rubygems.find_name('puppet-blacksmith').any?
require 'github_changelog_generator/task' if Bundler.rubygems.find_name('github_changelog_generator').any?
require 'open3'

def changelog_user
  return unless Rake.application.top_level_tasks.include? "changelog"
  returnVal = nil || JSON.load(File.read('metadata.json'))['author']
  raise "unable to find the changelog_user in .sync.yml, or the author in metadata.json" if returnVal.nil?
  puts "GitHubChangelogGenerator user:#{returnVal}"
  returnVal
end

def changelog_project
  return unless Rake.application.top_level_tasks.include? "changelog"
  returnVal = nil || JSON.load(File.read('metadata.json'))['name']
  raise "unable to find the changelog_project in .sync.yml or the name in metadata.json" if returnVal.nil?
  puts "GitHubChangelogGenerator project:#{returnVal}"
  returnVal
end

def changelog_future_release
  return unless Rake.application.top_level_tasks.include? "changelog"
  returnVal = JSON.load(File.read('metadata.json'))['version']
  raise "unable to find the future_release (version) in metadata.json" if returnVal.nil?
  puts "GitHubChangelogGenerator future_release:#{returnVal}"
  returnVal
end

PuppetLint.configuration.send('disable_relative')
# Have to regenerate the lint task that puppetlabs-spec-helper lays down
# because we can't override the ignore-paths otherwise.
Rake::Task[:lint].clear
PuppetLint::RakeTask.new(:lint) do |config|
  config.fail_on_warnings = true
  config.disable_checks = %w[
    80chars
    140chars
    class_inherits_from_params_class
    class_parameter_defaults
    disable_autoloader_layout
    documentation
    single_quote_string_with_variables
    only_variable_string
  ]
  config.ignore_paths = [
    '.vendor/**/*.pp',
    'bundle/**/*.pp',
    'pkg/**/*.pp',
    'spec/**/*.pp',
    'tests/**/*.pp',
    'types/**/*.pp',
    'vendor/**/*.pp',
    'Boltdir/**/*.pp',
  ]
end
PuppetSyntax.exclude_paths = ['plans/**/*', 'vendor/**/*', 'Boltdir/**/*']

if Bundler.rubygems.find_name('github_changelog_generator').any?
  GitHubChangelogGenerator::RakeTask.new :changelog do |config|
    raise "Set CHANGELOG_GITHUB_TOKEN environment variable eg 'export CHANGELOG_GITHUB_TOKEN=valid_token_here'" if Rake.application.top_level_tasks.include? "changelog" and ENV['CHANGELOG_GITHUB_TOKEN'].nil?
    config.user = "#{changelog_user}"
    config.project = "#{changelog_project}"
    config.future_release = "#{changelog_future_release}"
    config.exclude_labels = ['maintenance']
    config.header = "# Change log\n\nAll notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org)."
    config.add_pr_wo_labels = true
    config.issues = false
    config.merge_prefix = "### UNCATEGORIZED PRS; GO LABEL THEM"
    config.configure_sections = {
      "Changed" => {
        "prefix" => "### Changed",
        "labels" => ["backwards-incompatible"],
      },
      "Added" => {
        "prefix" => "### Added",
        "labels" => ["feature", "enhancement"],
      },
      "Fixed" => {
        "prefix" => "### Fixed",
        "labels" => ["bugfix"],
      },
    }
  end
else
  desc 'Generate a Changelog from GitHub'
  task :changelog do
    raise <<EOM
The changelog tasks depends on unreleased features of the github_changelog_generator gem.
Please manually add it to your .sync.yml for now, and run `pdk update`:
---
Gemfile:
  optional:
    ':development':
      - gem: 'github_changelog_generator'
        git: 'https://github.com/skywinder/github-changelog-generator'
        ref: '20ee04ba1234e9e83eb2ffb5056e23d641c7a018'
        condition: "Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.2.2')"
EOM
  end
end

desc 'Validate plans'
task :validate_plans do
  successful = Dir.glob('plans/**/*.pp').map do |f|
    command = ['puppet', 'parser', 'validate', '--tasks', f]
    print command.join(' ')
    output, status = Open3.capture2e(*command)
    if status.success?
      puts(' - ok')
    else
      puts " - failed\n#{output}"
    end
    status.success?
  end
  raise(RuntimeError, 'Could not validate all plans') if !successful.all? { |s| s == true }
end

desc "Run syntax, lint, and spec tests."
task :test => [
  :syntax,
  :validate_plans,
  :lint,
  :metadata_lint,
  'check:symlinks',
  'check:git_ignore',
  'check:dot_underscore',
  'check:test_file',
  :rubocop,
  :spec,
  :metadata,
]
