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

require_relative 'run.rb'

PROTOC_DOWNLOAD = {
  'osx' => {
    'name' => 'protoc.zip',
    'url' => 'https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-osx-x86_64.zip',
    'sha256' => '0decc6ce5beed07f8c20361ddeb5ac7666f09cf34572cca530e16814093f9c0c',
  },
  'linux' => {
    'name' => 'protoc.zip',
    'url' => 'https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip',
    'sha256' => '6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807',
  }
}
PROTOC_DIR = '_build/protoc'

def main
  current_platform = platform
  unless current_platform
    abort "Platform #{RUBY_PLATFORM} is not yet supported by #{$0}"
  end

  install_protoc(current_platform)
end

def install_protoc(current_platform)
  # protoc Protobuf compiler
  download(PROTOC_DOWNLOAD[current_platform])
  FileUtils.rm_rf(PROTOC_DIR)
  FileUtils.mkdir_p(PROTOC_DIR)
  run!(%W[unzip #{File.expand_path(PROTOC_DOWNLOAD[current_platform]['name'])}], PROTOC_DIR)
end

def platform
  case RUBY_PLATFORM
  when /darwin/ then 'osx'
  when /linux/  then 'linux'
  end
end

def download(source)
  file = source['name']
  sha = source['sha256']

  return if sha_match?(file, sha)

  run!(%W[curl -L -o #{file} #{source['url']}])

  abort "SHA256 check failed" unless sha_match?(file, sha)
end

def sha_match?(file, sha)
  File.exist?(file) && Digest::SHA256.file(file).hexdigest == sha
end

main
puts 'done'
