module Dunlop::FileZip

  def self.unzip(zipped_filename, unzipped_filename)
    case self.mime_type(zipped_filename)
    when "application/zip"
      if zipped_filename.to_s.end_with?('.xlsx') # .xlsx IS a zipfile # .to_s is because it can be a Pathname
        %x[ cp #{Shellwords.escape(zipped_filename)} #{Shellwords.escape(unzipped_filename)} ]
      else
        %x[ unzip -p #{Shellwords.escape(zipped_filename)} > #{Shellwords.escape(unzipped_filename)} ]
      end
    when "application/x-gzip"
      %x[ gzip -c -d #{Shellwords.escape(zipped_filename)} > #{Shellwords.escape(unzipped_filename)} ]
    when "text/plain"
      FileUtils.cp(zipped_filename, unzipped_filename)
    else
      raise "unsupported mime-type"
    end
  end

  def self.unzip_to_directory_and_junk_paths(zipped_filename, destination_directory)
    case self.mime_type(zipped_filename)
    when "application/zip"
      %x[ unzip -j #{Shellwords.escape(zipped_filename)} -d #{Shellwords.escape(destination_directory)} ]
    else
      raise "unsupported mime-type"
    end
  end

  def self.mime_type(filename)
    command = if /Darwin/i =~ %x[uname]
      "file -bI #{Shellwords.escape(filename)}"
    else
      "file -bi #{Shellwords.escape(filename)}"
    end

    case %x[#{command}]
    when /gzip/i
      "application/x-gzip"
    when /zip/i
      "application/zip"
    else
      "text/plain"
    end
  end

  def self.gzip(unzipped_filename, gzipped_filename)
    return if mime_type(unzipped_filename) == "application/x-gzip" #TODO: maybe the application using is is expecti a copy at the target location in this case?
    %x[cat #{Shellwords.escape(unzipped_filename)} | gzip -c > #{Shellwords.escape(gzipped_filename)}]
  end

end
