#!/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'

PROTO_GO_DOWNLOAD = {
  'name' => 'protobuf-1.2.0.zip',
  'url' => 'https://github.com/golang/protobuf/archive/v1.2.0.zip',
  'sha256' => '0621edfe304f96b7f57f05ca8892427bc874dd4f186b28792873ca440437f6b8'
}
PROTO_GO_DIR = '_build'

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

  install_protoc(current_platform)
  install_protoc_gen_go
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 install_protoc_gen_go
  download(PROTO_GO_DOWNLOAD)

  proto_go_src_parent_dir = File.join(PROTO_GO_DIR, 'src/github.com/golang')
  proto_go_src_dir = File.join(proto_go_src_parent_dir, 'protobuf')
  FileUtils.rm_rf(File.join(proto_go_src_dir))
  FileUtils.mkdir_p(proto_go_src_parent_dir)

  run!(%W[unzip #{File.expand_path(PROTO_GO_DOWNLOAD['name'])}], proto_go_src_parent_dir)
  FileUtils.mv(
    File.join(proto_go_src_parent_dir, PROTO_GO_DOWNLOAD['name'].sub(%r{\.zip$}, '')),
    File.join(proto_go_src_dir)
  )

  gopath = File.expand_path(PROTO_GO_DIR)
  run!(%W[/usr/bin/env GOPATH=#{gopath} go install github.com/golang/protobuf/protoc-gen-go])
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'
