version = node['cinc-client']['version']

debian_major_version = node['platform_version'].to_i.to_s

kernel_machine = node['kernel']['machine']
arch = case kernel_machine
       when 'x86_64'
         'amd64'
       when 'aarch64', 'arm64'
         'arm64'
       else
         kernel_machine
       end

package_filename = "cinc_#{version}-1_#{arch}.deb"
download_url = "https://downloads.cinc.sh/files/stable/cinc/#{version}/debian/#{debian_major_version}/#{package_filename}"
local_path = ::File.join('/tmp', package_filename)

remote_file local_path do
  source download_url
  mode '0644'
  action :create
  not_if "cinc-client -v | grep -q #{version}"
end

bash 'install_cinc' do
  code <<-EOH
      dpkg -i #{local_path}
    EOH
  environment({ 'PATH' => '/usr/sbin:/sbin:/usr/bin:/bin' })
  retries 10
  retry_delay 10
  not_if "cinc-client -v | grep -q #{version}"
  notifies :restart, 'service[chef-client]' if ::File.exist?('/etc/systemd/system/chef-client.service')
end
