#
# Cookbook Name:: protobuf-compiler
# 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'

tarball_sha1s = {
  '2.5.0' => '7f6ea7bc1382202fb1ce8c6933f1ef8fea0c0148',
  '2.4.1' => 'efc84249525007b1e3105084ea27e3273f7cbfb0',
  '2.3.0' => 'd0e7472552e5c352ed0afbb07b30dcb343c96aaf',
}

packages = nil

deb_packages = [
  'tar',
  'build-essential',
  'autoconf',
  'libtool'
]

rpm_packages = [
  'tar',
  'gcc-c++',
  'make',
  'autoconf',
  'automake',
  'libtool'
]

case node[:platform_family]
when 'debian'
  packages = deb_packages
when 'rhel'
  packages = rpm_packages
end

flavor = node['protobuf-compiler']['install_flavor']
case flavor
when 'package'
  package 'protobuf-compiler' do
    action :install
  end
when 'google'
  src_path = node['protobuf-compiler']['src_path']
  version = node['protobuf-compiler']['version']
  tarball = "protobuf-#{version}.tar.gz"
  downloaded_tarball = "#{src_path}/#{tarball}"
  
  archive_url = node['protobuf-compiler']['archive_url']
  if ! FileTest.directory? "#{src_path}/protobuf-#{version}" then
    remote_file downloaded_tarball do
      source "#{archive_url}/#{tarball}"
      action :create_if_missing
    end
  
    ruby_block "sha1 checksum #{downloaded_tarball}" do
      block do
        checksum = tarball_sha1s[version]
        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
  
    packages.each {|pkg|
      resources(:package => pkg) rescue package pkg do
        action :install
      end
    }
  
    bash "install_protobuf-#{version}" do
      cwd src_path
      code <<-EOC
        tar xvzf #{downloaded_tarball}
        cd protobuf-#{version}
        ./configure
        make
        make install
        ldconfig
      EOC
      creates "#{src_path}/protobuf-#{version}"
    end
  else
    log "#{src_path}: protobuf-#{version} already installed. "
  end
else
  Chef::Application.fatal!("Non supported flavor: #{flavor}")
end

