#
# Cookbook Name:: maven
# 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.
#

require 'digest/sha1'

file_cache_path = Chef::Config[:file_cache_path]
version = node['maven']['version']
install_root = "#{node['maven']['install_dir']}/apache-maven-#{version}"
tarball = "apache-maven-#{version}-bin.tar.gz"
tarball_sha1 = "#{tarball}.sha1"
downloaded_tarball = "#{file_cache_path}/#{tarball}"
downloaded_tarball_sha1 = "#{file_cache_path}/#{tarball_sha1}"

archive_url = node['maven']['archive_url']
if ! FileTest.directory? install_root then
  remote_file downloaded_tarball_sha1 do
    source "#{archive_url}/#{tarball_sha1}"
    action :create_if_missing
  end

  remote_file downloaded_tarball do
    source "#{archive_url}/#{tarball}"
    action :create_if_missing
  end

  ruby_block "sha1 checksum #{downloaded_tarball}" do
    block do
      checksum = File.read(downloaded_tarball_sha1)
      Chef::Log.info "#{tarball}: SHA1 = #{checksum}"
      actual_checksum = Digest::SHA1.file(downloaded_tarball).to_s
      Chef::Log.info "#{tarball}: actual SHA1 = #{actual_checksum}"
      if ! checksum.casecmp(actual_checksum) then
        Chef::Application.fatal!("Invalid SHA1 checksum of #{downloaded_tarball}, expected: #{checksum}")
      end
    end
    action :create
  end

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

  bash "install_maven-#{version}" do
    code <<-EOC
      tar xvzf #{downloaded_tarball} -C #{node['maven']['install_dir']}
    EOC
    creates install_root
  end
end

link "#{node['maven']['install_dir']}/apache-maven" do
  to install_root
  action [:delete, :create]
end

