#!/usr/bin/env ruby

require 'json'

begin
  parsed_file = File.read(ARGV[0])
rescue StandardError
  warn 'Unable to read go.sum file'
  exit(1)
end

dependencies = {
  "parsed" => [],
  "skipped" => []
}

parsed_file.each_line do |line|
  # Split on space
  # Example - github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
  # Validate 3 parts - name, version and checksum
  parts = line.split
  if parts.length == 3
    names = parts[0].split("/")
    dependencies["parsed"].append(
      {
        "namespace" => names[0..-2].join("/").to_s,
        "name" => names[-1].to_s,
        "version" => parts[1].to_s.gsub('/go.mod', ''),
        "checksum" => parts[2].to_s.gsub('h1:', '')
      }
    )
  else
    dependencies["skipped"].append(line)
  end
end

puts dependencies.to_json
