#! /usr/bin/env ruby
# -*- coding: utf-8 -*-
# Copyright: Copyright © Huawei Technologies Co., Ltd. 2022. All rights reserved. Create: 2022-08-04
# frozen_string_literal: true

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

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

options = OptionParser.new do |opts|
  opts.banner = 'Usage: ccb build-image key1=val1'
  opts.separator ''
  opts.separator '    eg.1: ccb build-image pipeline_id=xxx'
  opts.separator ''

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

options.parse!(ARGV)

if ARGV.empty?
  puts(options)
  exit
end

def build_image_response(jwt, hash, my_config)
  ccb_api_client = CcbApiClient.new(my_config['GATEWAY_IP'], my_config['GATEWAY_PORT'])
  response = ccb_api_client.build_image(jwt, hash.to_json)
  return response
end

def build_image_result(jwt, hash, my_config)
  jwt = load_jwt?(force_update = true)
  response = build_image_response(jwt, hash, my_config)

  puts response.body
end

hash = get_no_option_paras!(ARGV)[0]
pipeline_id = hash['pipeline_id'] || ''

if pipeline_id.empty?
  puts "pipeline_id can't be empty"
  exit
end

my_config = load_my_config
jwt = load_jwt?

required_keys = %w[GATEWAY_IP GATEWAY_PORT]

required_keys.each do |var|
  unless my_config.has_key?(var) && !my_config[var].nil?
    puts "config #{var} not found"
    exit
  end
end


build_image_result(jwt, hash, my_config)
