require 'tmpdir'
require 'open3'

if ARGV.length < 2
  $stderr << <<EOF
Usage: gen_all.rb <path_to_rubystubs>
EOF
  #exit(1)
end

#rubystubs_dir = ARGV[1]

URL = 'https://ftp.ruby-lang.org/pub/ruby/'
SCRIPT_PATH = File.expand_path File.dirname(__FILE__)
RUBY_VERSIONS = %w(2.6.0-preview2) #%w(1.8.7-p358 1.9-stable 2.0-stable 2.1-stable 2.2-stable 2.3-stable 2.4-stable 2.5-stable 2.6.0-preview2)

def download_ruby_version(version)
  filename = "ruby-#{version}.tar.bz2"
  p `curl -sSL #{URL}#{filename} -o #{filename}` unless File.file?(filename)
  filename
end


RubyDownloads = 'rubies-downloads'
RubyReleases = 'rubies-releases'
RubyStubs = 'rubies-stubs'
Dir.mkdir(RubyDownloads) unless File.directory?(RubyDownloads)
Dir.mkdir(RubyReleases) unless File.directory?(RubyReleases)
Dir.mkdir(RubyStubs) unless File.directory?(RubyStubs)
Dir.chdir(RubyDownloads)
RUBY_VERSIONS.each do |version|
  $stderr.puts "Downloading #{version}"
  filename = download_ruby_version(version)
  $stderr.puts "Extracting #{version}"
  `tar -xf #{filename} -C "../#{RubyReleases}"`
end

Dir.chdir("../#{RubyReleases}")
Dir["*"].each do |dir|
  dir =~ /ruby-(\d+)\.(\d+)\..+/
  rubystubs_dir = "rubystubs#{$1}#{$2}"
  $stderr.puts "Regenerating stubs in #{rubystubs_dir}"
  `rm -rf #{dir}/spec`
  stdout, stderr, status = Open3.capture3("ruby #{SCRIPT_PATH}/gen_stubs.rb  --source-directory=#{dir} -b -v -s #{dir} --output-directory ../#{RubyStubs}/#{rubystubs_dir}")
  if status != 0
    $stderr.puts "EXIT CODE #{status}"
    $stderr.puts "Stdout: #{stdout}\nStderr: #{stderr}"
    next
  end
end
