#
# Author:: Sander Botman <sbotman@schubergphilis.com>
# Cookbook Name:: windows
# Provider:: font
#
# Copyright:: 2014, Schuberg Philis BV.
#
# 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.
#

use_inline_resources

include Windows::Helper

def load_current_resource
  require 'win32ole'
  fonts_dir = WIN32OLE.new('WScript.Shell').SpecialFolders('Fonts')
  @current_resource = Chef::Resource::WindowsFont.new(@new_resource.name)
  @current_resource.file(win_friendly_path(::File.join(fonts_dir, @new_resource.file)))
  @current_resource
end

# Check to see if the font is installed
#
# === Returns
# <true>:: If the font is installed
# <false>:: If the font is not instaled
def font_exists?
  ::File.exist?(@current_resource.file)
end

def get_cookbook_font
  font_file = @new_resource.file
  if @new_resource.source
    remote_file font_file do
      action  :nothing
      source  "file://#{new_resource.source}"
      path    win_friendly_path(::File.join(ENV['TEMP'], font_file))
    end.run_action(:create)
  else
    cookbook_file font_file do
      action    :nothing
      cookbook  cookbook_name.to_s unless cookbook_name.nil?
      path      win_friendly_path(::File.join(ENV['TEMP'], font_file))
    end.run_action(:create)
  end
end

def del_cookbook_font
  file ::File.join(ENV['TEMP'], @new_resource.file) do
    action :delete
  end
end

def install_font
  require 'win32ole'
  fonts_dir = WIN32OLE.new('WScript.Shell').SpecialFolders('Fonts')
  folder = WIN32OLE.new('Shell.Application').Namespace(fonts_dir)
  folder.CopyHere(win_friendly_path(::File.join(ENV['TEMP'], @new_resource.file)))
  Chef::Log.debug("Installing font: #{@new_resource.file}")
end

action :install do
  if font_exists?
    Chef::Log.debug("Not installing font: #{@new_resource.file}, font already installed.")
    new_resource.updated_by_last_action(false)
  else
    get_cookbook_font
    install_font
    del_cookbook_font
    new_resource.updated_by_last_action(true)
  end
end
