#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require_relative '../lib/build_account_info'
require 'optparse'

if $PROGRAM_NAME == __FILE__
  option = {
    'my_email' => `git config --global user.email`.chomp,
    'my_name' => `git config --global user.name`.chomp,
    'lab' => `awk '/^lab:\s/ {print $2; exit}' /etc/compass-ci/defaults/*.yaml`.chomp,
    'my_ssh_pubkey' => []
  }

  is_search = false

  options = OptionParser.new do |opts|
    opts.banner = "Usage: build-my-info [-e email] [-n name] [-a account] [-l lab] [-k pubkey_file] [-t]\n"
    opts.banner += "       build-my-info [-e email] [-s]\n"

    opts.separator ''
    opts.separator 'options:'

    opts.on('-e email', 'my_email') do |email|
      option['my_email'] = email
    end

    opts.on('-a my_account', 'my_account') do |account|
      unless account =~ /^\w[\w|\-|_]+$/
        message = "my_account should only contains letters, digits, '-' or '_'\n\n"
        puts message
        exit
      end

      option['my_account'] = account
    end

    opts.on('-n name', 'my_name') do |name|
      option['my_name'] = name
    end

    opts.on('-l lab', 'lab') do |lab|
      option['lab'] = lab
    end

    opts.on('-t', 'my_token') do
      option['my_token'] = %x(uuidgen).chomp
    end

    opts.on('-k pubkey_file', 'pubkey_file') do |pubkey_file|
      my_ssh_pubkey = File.read(pubkey_file).chomp
      option['my_ssh_pubkey'].insert(0, my_ssh_pubkey)
    end

    opts.on('-s', 'search my_info') do
      is_search = true
    end

    opts.on_tail('-h', 'show this message') do
      puts opts
      exit
    end
  end

  options.parse!

  if is_search
    my_info, = search_account_info(option)
    puts my_info.to_json
  else
    build_account_info(option)
  end

end
