#
# Cookbook Name:: apt_utils
# Recipe:: mirror
#
# Copyright 2013, whitestar
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

::Chef::Recipe.send(:include, Commons::PackageUtils)

pkg = 'apt-mirror'  # CentOS: in the EPEL
resources(:package => pkg) rescue package pkg do
  action :install
end

mirror_user = node['apt_utils']['mirror']['user']
base_path = node['apt_utils']['mirror']['base_path']

resources(:group => mirror_user) rescue group mirror_user do
  system true
  action :create
end

resources(:user => mirror_user) rescue user mirror_user do
  gid mirror_user
  system true
  home base_path
  shell '/bin/sh'
  password nil
  action :create
end

bash "#{base_path} - change owner to #{mirror_user}:#{mirror_user} recursively." do
  code <<-EOC
    chown -R #{mirror_user}:#{mirror_user} #{base_path}
  EOC
end

mirror_list_path = nil
httpd_service = get_httpd_pkg_name
httpd_conf_path = nil

case node[:platform_family]
when 'debian'
  mirror_list_path = '/etc/apt/mirror.list'
  httpd_conf_path = "/etc/#{httpd_service}/conf.d/apt-mirror"
when 'rhel'
  mirror_list_path = '/etc/apt-mirror.list'
  httpd_conf_path = "/etc/#{httpd_service}/conf.d/apt-mirror.conf"
end

template mirror_list_path do
  source 'etc/apt/mirror.list'
  owner 'root'
  group 'root'
  mode '0644'
end

pkg = get_cron_pkg_name
resources(:package => pkg) rescue package pkg do
  action :install
end

template '/etc/cron.d/apt-mirror' do
  source 'etc/cron.d/apt-mirror'
  owner 'root'
  group 'root'
  mode '0644'
end

pkg = httpd_service
resources(:package => pkg) rescue package pkg do
  action :install
end

resources(:service => httpd_service) rescue service httpd_service do
  action [:enable, :start]
  supports :status => true, :restart => true, :reload => true
end

template httpd_conf_path do
  source 'etc/apache2/conf.d/apt-mirror'
  owner 'root'
  group 'root'
  mode '0644'
  notifies :restart, "service[#{httpd_service}]"
end

