yum_repos = node['yum']['repos']
repos_databag = node['yum']['databag']

disable_mirrors = node['yum']['disable_mirrors']
force_centos_repos_priority = node['yum']['force_centos_repos_priority']
repo_file_names = node['yum']['repo_file_names']
repo_name_prefix = node['yum']['repo_name_prefix']

if yum_repos
  yum_repos.each do |yum_repo_name, yum_repo|
    yum_host = yum_repo['host']
    yum_exclude = yum_repo['exclude']

    begin
      credentials_databag = data_bag_item(repos_databag, yum_repo_name)
      yum_user = credentials_databag['username']
      yum_password = credentials_databag['password']
    rescue
      Chef::Log.warn("Cannot find item #{yum_repo_name} for databag #{repos_databag}; using unauthenticated YUM repo")
    end

    yum_repo_url = if yum_user && yum_password
                     "http://#{yum_user}:#{yum_password}@#{yum_host}/#{yum_repo_name}/"
                   else
                     "http://#{yum_host}/#{yum_repo_name}/"
                   end

    # Add Yum Repository to /etc/yum.repos.d
    yum_repository yum_repo_name do
      description "#{yum_repo_name} repo"
      url yum_repo_url
      exclude yum_exclude
      metadata_expire '90'
      gpgcheck false
      action :add
    end
  end
end

if force_centos_repos_priority
  repo_file_names.each do |repo_name|
    execute "force-repo-priority-to-#{repo_name}" do
      command "sed -i '/name=#{repo_name_prefix}/a priority=1' /etc/yum.repos.d/#{repo_name}"
      action :run
      not_if "cat /etc/yum.repos.d/#{repo_name} | grep 'priority=1'"
      only_if "ls /etc/yum.repos.d/#{repo_name}"
    end
  end
end

if disable_mirrors
  node.default['yum']['epel']['baseurl'] = 'http://download.fedoraproject.org/pub/epel/$releasever/$basearch'
  execute 'remove-mirrors' do
    command 'sed -i s/mirrorlist=/#mirrorlist=/g /etc/yum.repos.d/*'
    action :run
  end
  execute 'enable-baseurl' do
    command 'sed -i s/#baseurl=/baseurl=/g /etc/yum.repos.d/*'
    action :run
  end
end

include_recipe 'yum::default'
include_recipe 'yum-epel::default'
