#!/usr/bin/env ruby require "birst_command" require "optparse" module BirstCL extend self def run set_options if @options[:version] puts "Birst_Command Version: #{Birst_Command::VERSION}" exit end if @options[:encrypt_password] encrypt_password(@options[:encrypt_password]) end if @options[:command] read_config_file execute_command end end def set_options @options = {} OptionParser.new do |opts| opts.banner = "Usage: birstcl -c -a " opts.on("--verbose", "--[no-]verbose", "Run verbosely") do |v| @options[:verbose] = v end @options[:version] = false opts.on("--version", "--version", "Print version") do |v| @options[:version] = true end opts.on("-h","--help", "Show this message") do puts opts exit end @options[:encrypt_password] = nil opts.on("-e","--encrypt_password ","Generates an encrypted version of PASSWORD that needs to be placed in ~/.birstcl") do |opt| @options[:encrypt_password] = opt end @options[:command] = nil opts.on("-c","--command ","COMMAND is the snake_case Birst web API command") do |opt| @options[:command] = opt end @options[:arguments] = {} opts.on("-a","--args ","ARGUMENTS is a JSON string of arguments to COMMAND") do |opt| @options[:arguments] = eval(opt) end =begin @options[:json_full_path] = nil opts.on("-f","--file ","Path to JSON file containing command") do |opt| @options[:json_full_path] = opt end =end @options[:config_full_path] = "#{ENV['HOME']}/.birstcl" opts.on("-s","--config_file ", "Path to config file containing credentials (default: $HOME/.birstcl)") do |opt| @options[:config_full_path] = opt end @options[:write_cookie_full_path] = nil opts.on("-w","--write_cookie_file ", "Path to cookie file to write") do |opt| @options[:write_cookie_full_path] = opt end @options[:read_cookie_full_path] = nil opts.on("-r","--read_cookie_file ", "Path to cookie file to read") do |opt| @options[:read_cookie_full_path] = opt end end.parse! end def read_config_file Birst_Command::Config.read_config(@options[:config_full_path]) end def encrypt_password(password) Birst_Command::Password.generate_keys(verbose: true) puts <<-EOF.unindent ... Use this encrypted password in your .birstcl file: "#{Birst_Command::Password.encrypt(password)}" EOF end def write_cookie_file(file_full_path) return nil if file_full_path.nil? File.open(file_full_path, 'w') {|f| f.write(Marshal.dump(@session_cookie)) } end def read_cookie_file(file_full_path) return nil if file_full_path.nil? Marshal.load(File.read(file_full_path)) end def execute_command @session_cookie = read_cookie_file(@options[:read_cookie_full_path]) output = {} output[:command] = @options[:command] output[:arguments] = @options[:arguments] Birst_Command::Session.start use_cookie: @session_cookie do |bc| output[:token] = bc.token output[:auth_cookies] = bc.auth_cookies.inspect output[:result] = bc.send(@options[:command], @options[:arguments]) @session_cookie = bc.auth_cookies end puts "#{JSON.pretty_generate output}" write_cookie_file(@options[:write_cookie_full_path]) end end BirstCL.run