module Dunlop::FileZip

  def self.unzip(zipped_filename, unzipped_filename)
    case self.mime_type(zipped_filename)
    when "application/zip"
      %x[ unzip -p #{zipped_filename} > #{unzipped_filename} ]
    when "application/x-gzip"
      %x[ gzip -c -d #{zipped_filename} > #{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 #{zipped_filename} -d #{destination_directory} ]
    else
      raise "unsupported mime-type"
    end
  end

  def self.mime_type(filename)
    command = if /Darwin/i =~ %x[uname]
      "file -bI #{filename}"
    else
      "file -bi #{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 #{unzipped_filename} | gzip -c > #{gzipped_filename}]
  end

end
