#!/usr/bin/env ruby
require 'json'
require 'fileutils'

FileUtils.mkdir_p("packages")

zookeeper_download_html = 'packages/zookeeper-download.html'
zookeeper_versions_json = 'packages/zookeeper-versions.json'
`curl https://archive.apache.org/dist/zookeeper/ > #{zookeeper_download_html}` unless File.exist?(zookeeper_download_html)

zookeeper_download_text = IO.read(zookeeper_download_html)
zookeeper_versions = zookeeper_download_text.scan(/(zookeeper-(\d+.\d+.\d+)\/<\/a>\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}))/)
.uniq
.sort_by { |pattern| pattern[1] }
.reverse
.map.with_index do |pattern, index|
    puts "- `#{pattern[1]}`" if index < 10

    {
        version: pattern[1],
        date: pattern[2]
    }
end

File.open(zookeeper_versions_json, "w:utf-8") do |file|
    file.puts(JSON.pretty_generate(zookeeper_versions))
end
puts "View all zookeeper versions in #{zookeeper_versions_json}."