namespace :image_compression do
  desc 'Optimize images with pngcrush and jpegoptim'
  task :process do

    # Check for pngcrush
    if (!`which pngcrush`.empty? rescue false) # rescue on environments without `which` (windows)

      # Crush all .png files
      run "find #{shared_path}/assets/ -type f -name '*.png' -print0 | xargs -0 pngcrush -q -e .crushed"

      # Replace original with crushed version
      run "find #{shared_path}/assets/ -type f -name '*.crushed' -print0 | xargs -0 -n1 sh -c 'mv $0 ${0%.crushed}.png'"

    else
      logger.info "WARNING: pngcrush not found. Skipping..."
    end

    # Check for jpegoptim
    if (!`which jpegoptim`.empty? rescue false) # rescue on environments without `which` (windows)

      # Crush all .jpg files in place
      run "find #{shared_path}/assets/ -type f -name '*.jpg' -print0 | xargs -0 -n1 sh -c 'jpegoptim --quiet --strip-all $0'"

    else
      logger.info "WARNING: jpegoptim not found. Skipping..."
    end
  end

  # Set to run after assets:precompile task
  after "deploy:assets:precompile", "image_compression:process"
end