#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/environment.rb'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: images_provider_transfer.rb source_provider destination_provider [options]"

  opts.on("-d", "--dryrun", "No action executed") do |d|
    options[:dryrun] = d
  end

  opts.on("-v", "--verbose", "Verbose") do |v|
    options[:verbose] = v
  end

end.parse!

if ARGV.blank?
  puts 'Error : no argument, use -h or --help for help'
  exit
elsif ARGV.size < 2
  puts 'Error : not enough arguments, 2 are required. Use -h or --help for help'
  exit
elsif ARGV.size > 2
  puts 'Error : too many arguments, 2 only are required. Use -h or --help for help'
  exit
end

src_provider_sk = ARGV[0]
dest_provider_sk = ARGV[1]
log_filename = "images_transfer_#{src_provider_sk}_to_#{dest_provider_sk}_#{Time.now.strftime("%Y%m%d-%H%M%S")}.log"
log_file = File.open(log_filename,"a+")
src_prov = Provider.find_by(string_key: src_provider_sk)
dest_prov = Provider.find_by(string_key: dest_provider_sk)
if src_prov.blank? || dest_prov.blank?
  puts "Error : source provider #{src_provider_sk} not found" if src_prov.blank?
  puts "Error : destination provider #{dest_provider_sk} not found" if dest_prov.blank?
  exit false
else
  #To be sure to get the correct string_key case
  src_provider_sk = src_prov.string_key
  dest_provider_sk = dest_prov.string_key
end

src_imgs = Image.where(images: {provider_id: src_prov.id})
if src_imgs.blank?
  log_file.write("Warning : no images found for #{src_provider_sk}.\n")
else
  log_file.write("Info : #{src_imgs.count} images found for #{src_provider_sk}\n")
  i=0
  src_imgs.each do |src_img|
    i+=1
    log_file.write("Image n°#{i}")
    #prefix = src_img.file_name.partition(".")[0]
    noprefix_name = src_img.file_name.partition(".")[2]
    src_thumb_location = src_img.thumb_location
    src_medium_location = src_img.medium_location
    dest_thumb_location = src_thumb_location.gsub(/\/#{src_provider_sk}/i,"\/#{dest_provider_sk}")
    dest_medium_location = src_medium_location.gsub(/\/#{src_provider_sk}/i,"\/#{dest_provider_sk}")
    dest_thumb_path = File.dirname(dest_thumb_location)
    dest_medium_path = File.dirname(dest_medium_location)
    begin
      src_img.update(provider_id: dest_prov.id, file_name: "#{dest_provider_sk}.#{noprefix_name}", thumb_location: dest_thumb_location, medium_location: dest_medium_location) unless options[:dryrun]
      log_file.write("Debug : update image id: #{src_img.id} (command : src_img.update(provider_id: #{dest_prov.id}, file_name: '#{dest_provider_sk}.#{noprefix_name}', thumb_location: #{dest_thumb_location}, medium_location: #{dest_medium_location}) ).\n") if options[:verbose]
      FileUtils.mkdir_p "#{Rails.root}/public/#{dest_thumb_path}" unless options[:dryrun]
      log_file.write("Debug : FileUtils.mkdir_p #{Rails.root}/public/#{dest_thumb_path}\n") if options[:verbose]
      FileUtils.mkdir_p "#{Rails.root}/public/#{dest_medium_path}" unless options[:dryrun]
      log_file.write("Debug : FileUtils.mkdir_p #{Rails.root}/public/#{dest_medium_path}\n") if options[:verbose]
      FileUtils.mv("#{Rails.root}/public/#{src_thumb_location}", "#{Rails.root}/public/#{dest_thumb_location}", force: true) unless options[:dryrun]
      log_file.write("Debug : FileUtils.mv (#{Rails.root}/public/#{src_thumb_location},#{Rails.root}/public/#{dest_thumb_location})\n") if options[:verbose]
      FileUtils.mv("#{Rails.root}/public/#{src_medium_location}", "#{Rails.root}/public/#{dest_medium_location}", force: true) unless options[:dryrun]
      log_file.write("Debug : FileUtils.mv (#{Rails.root}/public/#{src_medium_location},#{Rails.root}/public/#{dest_medium_location})\n") if options[:verbose]
    rescue => e
      log_file.write("ERROR : error while moving image with original_filename #{src_img.original_filename} from #{src_provider_sk} to #{dest_provider_sk} : #{e}\n")
    else
      log_file.write("Info : Image with original_filename '#{src_img.original_filename}' and id #{src_img.id} moved from #{src_provider_sk} to #{dest_provider_sk}.\n")
    end
  end
end

log_file.close
puts "Transfer completed, log file : #{log_filename}"