#
# Cookbook Name:: apt_utils
# Recipe:: aptly
#
# Copyright 2017, 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.
#

platform = node['platform']
platform_version = node['platform_version']

apt_get_update = 'apt-get_update'
resources(execute: apt_get_update) rescue execute apt_get_update do
  command 'apt-get update'
  action :nothing
end

apt_repo_config = node['apt_utils']['aptly']['apt_repo']
bash 'apt-key_adv_aptly_key' do
  code <<-"EOH"
    apt-key adv --keyserver #{apt_repo_config['keyserver']} --recv-keys #{apt_repo_config['recv-keys']}
  EOH
  action :nothing
  notifies :run, "execute[#{apt_get_update}]", :immediately
  not_if "apt-key list | grep 'Andrey Smirnov'"
end

if (platform == 'debian' && platform_version < '8.0') \
  || (platform == 'ubuntu' && platform_version < '16.04')
  template '/etc/apt/sources.list.d/aptly.list' do
    source  'etc/apt/sources.list.d/aptly.list'
    owner 'root'
    group 'root'
    mode '0644'
    notifies :run, 'bash[apt-key_adv_aptly_key]', :before
    notifies :run, "execute[#{apt_get_update}]", :immediately
  end
end

pkg_name = 'aptly'
resources(package: pkg_name) rescue package pkg_name do
  action :install
  notifies :run, 'bash[apt-key_adv_aptly_key]', :before
end

template '/etc/aptly.conf' do
  source  'etc/aptly.conf'
  owner 'root'
  group 'root'
  mode '0644'
  action :create
end

aptly_user = node['apt_utils']['aptly']['user']
user aptly_user do
  action :create
  not_if { aptly_user == 'root' }
end

directory node['apt_utils']['aptly']['conf']['rootDir'] do
  owner aptly_user
  group 'root'
  mode '0755'
  action :create
end
