#!/usr/bin/env ruby
#
# frozen_string_literal: true

# Create a Git repo on git.netflux.io

require 'json'
require 'net/http'
require 'optparse'
require 'uri'

options = {}
banner = 'Usage: createrepo [options] <reponame>'

OptionParser.new do |opts|
  opts.banner = banner

  opts.on('--private', 'Make repo private') do |v|
    options[:private] = v
  end

  opts.on('-d', '--description=DESC', 'Description') do |v|
    options[:description] = v
  end
end.parse!

options[:name] = ARGV.pop.to_s.strip
if options[:name].empty?
  puts banner
  exit 1
end

auth_token = ENV['GIT_NETFLUX_IO_TOKEN']
if !auth_token || auth_token.empty?
  puts 'Env var GIT_NETFLUX_IO_TOKEN must be set'
  exit 1
end

uri = URI('https://git.netflux.io/api/v1/user/repos')
auth_string = "token #{auth_token}"

req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json', 'Authorization' => auth_string)
req.body = options.to_json

Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  resp = http.request(req)
  if resp.code != '201'
    begin
      errmsg = JSON.parse(resp.body)
      puts errmsg['message']
    rescue JSON::ParserError
      puts resp.body
    end
    exit 1
  end

  repo = JSON.parse(resp.body)
  puts "git remote add origin #{repo['ssh_url']}"
end