#
# Cookbook Name:: jce_policy
# Recipe:: default
#
# 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.
#

cookie_jce_policy6 = 'oraclelicense=accept-securebackup-cookie;gpw_e24=http://www.oracle.com'
cookie_jce_policy7 = 'oraclelicensejce-7-oth-JPR=accept-securebackup-cookie;gpw_e24=http://www.oracle.com'

cookie = ''
download_url = ''
zip_file = ''
unzipped_dir = ''
case node['java']['jdk_version']
  when '6'
    cookie = cookie_jce_policy6
    download_url = node['jce_policy']['6']['url']
    zip_file = 'jce_plicy-6.zip'
    unzipped_dir = 'jce'
  when '7'
    cookie = cookie_jce_policy7
    download_url = node['jce_policy']['7']['url']
    zip_file = 'UnlimitedJCEPolicyJDK7.zip'
    unzipped_dir = 'UnlimitedJCEPolicy'
end

if node['jce_policy']['oracle']['accept_oracle_download_terms']
  package 'curl' do
    action :install
  end

  downloaded_file = "#{Chef::Config[:file_cache_path]}/#{zip_file}"
  bash "download_jce_policy#{node['java']['jdk_version']}" do
    code <<-EOC
      curl -L --cookie "#{cookie}" #{download_url} -o #{downloaded_file}
    EOC
    creates downloaded_file
  end
else
  Chef::Application.fatal!("You must set the attribute node['jce_policy']['oracle']['accept_oracle_download_terms'] to true if you want to download directly from the oracle site!")
end

package 'unzip' do
  action :install
end

bash "install_jce_policy#{node['java']['jdk_version']}" do
  code <<-EOC
    unzip #{downloaded_file} -d #{Chef::Config[:file_cache_path]}
    mv #{node['java']['java_home']}/jre/lib/security/US_export_policy.jar \\
       #{node['java']['java_home']}/jre/lib/security/US_export_policy.jar.dist
    mv #{node['java']['java_home']}/jre/lib/security/local_policy.jar \\
       #{node['java']['java_home']}/jre/lib/security/local_policy.jar.dist
    cp #{Chef::Config[:file_cache_path]}/#{unzipped_dir}/*.jar \\
       #{node['java']['java_home']}/jre/lib/security
  EOC
  creates "#{node['java']['java_home']}/jre/lib/security/US_export_policy.jar.dist"
end

