#!/usr/bin/ruby

def find_mount_point
  Dir.open("/media").each do |d|
    music = "/media/#{d}/MUSIC"
    return Dir.open(music) if File.directory? music 
  end

  $stderr.puts "Cannot find where your player is mounted"
  exit 1
end

def find_covers_dir
  path = "#{ENV['HOME']}/.covers"
  begin
    Dir.open(path)
  rescue Errno::ENOENT
    $stderr.puts "You don't have covers in #{path}"
    exit 1
  end
end

def check_dir(mount, covers)
  #puts "check #{mount}"
  
  Dir.open(mount).each do |f|
    new_mount = "#{mount}/#{f}"
    
    if File.directory? new_mount and not (f =~ /^\./) then
      new_covers = "#{covers}/#{f}"
      jpg = "#{new_covers}.jpg"
      folder = "#{new_mount}/Folder.jpg"
      
      if File.directory? new_covers then
        check_dir(new_mount, new_covers)
      elsif File.exists? folder then
        # All good
      elsif File.exists? jpg then
        puts "Copying #{jpg}"
        cmd = "cp \"#{jpg}\" \"#{folder}\""
        system cmd
      else
        puts "Warning: No cover for #{f} (expected #{new_covers})"
      end
    end
  end
end

def sync_covers
  mount = find_mount_point
  covers = find_covers_dir

  puts "Finding missing covers for #{mount.path}"

  check_dir(mount.path, covers.path)

  puts "Syncing filesystem"
  system "sync"
end

sync_covers
