property :job_name, String, name_property: true

property :description, String, default: 'Generated by Chef'
property :display_name, String
property :properties, Hash, default: {}
property :scm, Hash, default: {}, callbacks: { 'scm can only contain one key/value' => proc { |v| v.length <= 1 } }
property :script_path, String, default: 'Jenkinsfile'
property :lightweight, [true, false], default: true
property :script, String, default: "node { echo 'hello world'}"
property :sandbox, [true, false], default: false

property :template, String, default: 'pipeline-config.xml.erb'
property :include_templates, Array, default: []
property :auto_create_folders, [true, false], default: node['chef_jenkins']['auto_create_folders']

action :create do
  folder_name = ::File.dirname(new_resource.job_name)
  if new_resource.auto_create_folders && !folder_name.eql?('.')
    folder_name = ::File.dirname(new_resource.job_name)
    chef_jenkins_folder folder_name
  end

  xml = "#{Chef::Config[:file_cache_path]}/#{new_resource.job_name}.xml"

  directory ::File.dirname(xml) do
    recursive true
  end

  declare_resource(:template, xml) do
    source new_resource.template
    variables(
      description: new_resource.description,
      display_name: new_resource.display_name,
      properties: new_resource.properties,
      scm: new_resource.scm,
      script_path: new_resource.script_path,
      lightweight: new_resource.lightweight,
      script: new_resource.script.encode(xml: :text),
      sandbox: new_resource.sandbox,

      cookbook: new_resource.cookbook_name,
      include_templates: new_resource.include_templates
    )
    helpers(ChefJenkins::Helper)
    cookbook new_resource.include_templates.include?(new_resource.template) ? new_resource.cookbook_name : 'chef_jenkins'
  end

  jenkins_job new_resource.job_name do
    config xml
  end
end

action :delete do
  jenkins_job new_resource.job_name do
    action :delete
  end
end

action_class.class_eval do
  include ChefJenkins::Helper
end
