#! /usr/bin/env ruby

# frozen_string_literal: true

LKP_SRC = ENV['LKP_SRC'] || File.dirname(File.dirname(File.dirname(File.realpath($PROGRAM_NAME))))

require 'yaml'
require 'json'
require 'optparse'
require "#{LKP_SRC}/sbin/cli/ccb_common"
require "#{LKP_SRC}/sbin/cli/ccb_api_client"

json_path = nil
yaml_path = nil

options = OptionParser.new do |opts|
  opts.banner = 'Usage: ccb update <index> <os_project> k=v|--json JSON|--yaml YAML --sort --field'
  opts.separator '    eg.1: ccb update projects openEuler:Mainline -j example.json'
  opts.separator '    example.json: {"users+": {"zhangsan": "maintainer", "lisi": "reader"}, "users-": ["wangwu"]}'
  opts.separator 'options:'

  opts.on('-j', '--json <path>', 'json file') do |j|
    json_path = j
  end
  opts.on('-y', '--yaml <path>', 'yaml file') do |y|
    yaml_path = y
  end

  opts.on('-h', '--help', 'show this message') do
    puts options
    exit
  end
end

if $PROGRAM_NAME == __FILE__
  if ARGV.empty?
    puts options
    exit
  end
  options.parse!(ARGV)

  hash_paras, array_paras = get_no_option_paras!(ARGV, json_path, yaml_path)

  if array_paras.length == 0
    raise 'please input update index'
  elsif array_paras.length == 1
    raise 'please input project name'
  elsif array_paras.length == 2
    index = array_paras[0]
    os_project = array_paras[1]
  else
    raise 'too much parameter error'
  end
    
  request_info = hash_paras
  jwt = load_jwt?
  config = load_my_config
  api_client = CcbApiClient.new(config['GATEWAY_IP'], config['GATEWAY_PORT'])
  response = api_client.update_os_project(jwt, os_project, request_info.to_json)
  response = JSON.parse(response)
  if response.has_key?('status_code') and response['status_code'] == 401
    jwt = load_jwt?(force_update=true) # jwt may timeout and retry once
    api_client = CcbApiClient.new(config['GATEWAY_IP'], config['GATEWAY_PORT'])
    response = api_client.update_os_project(jwt, os_project, request_info.to_json)
    response = JSON.parse(response)
  end
  check_return_code(response)
  puts JSON.pretty_generate(response)
end
