require "slop" module MuchKeys class CLI attr_reader :mode def initialize(arguments) # I'd like to not be doing this kind of check # But this is tricky because we need to know # later if help was invoked so we don't execute run with blank options. @help_invoked = false parsed = parse_options(arguments) return if @help_invoked begin set_primary_mode rescue MuchKeys::CLIOptionsError => e puts e.message puts @opts end configure_muchkeys end def parse_options(arguments) @opts = Slop.parse arguments do |o| o.bool "-e", "--encrypt", "Encrypt keys from a file to put in consul." o.bool "-d", "--decrypt", "Decrypt keys from consul." o.bool "-p", "--plain", "Fetch plaintext key from consul." o.string "--consul_url", "Consul server http address", default: "http://localhost:8500" o.string "--private_key", "Location of your private key" o.string "--public_key", "Location of your public key" # add -f o.string "--file", "File to encrypt" o.string "-c", "--consul_key", "Consul key to decrypt" o.on "-h", "--help" do # Save the fact we ran help so when run() runs, it prints help and exits. @help_invoked = true end end end def set_primary_mode(options=@opts) MuchKeys::CLI::Validator.validate_primary_mode_option(options) @mode = select_primary_mode(options) end def configure_muchkeys(options=@opts) MuchKeys.configure do |config| config.consul_url = options[:consul_url] config.public_key = options[:public_key] config.private_key = options[:private_key] end end # this guy figures out the appropriate action to take given CLI options def run if @opts[:help] puts @opts return end if @opts[:encrypt] MuchKeys::CLI::Validator.validate_encrypt(file: @opts[:file], public_key: @opts[:public_key]) encrypt(@opts[:file], @opts[:public_key]) elsif @opts[:decrypt] MuchKeys::CLI::Validator.validate_decrypt(consul_key: @opts[:consul_key], public_key: @opts[:public_key], private_key: @opts[:private_key]) decrypt(@opts[:consul_key], @opts[:public_key], @opts[:private_key]) elsif @opts[:plain] plain(@opts[:consul_key]) end end def encrypt(file, public_key) string_to_encrypt = File.read(file) puts secret_adapter.encrypt_string(string_to_encrypt, public_key) end def decrypt(consul_key, public_key, private_key) puts MuchKeys.fetch_key(consul_key, public_key:public_key, private_key:private_key) end def plain(consul_key) puts MuchKeys.fetch_key(consul_key) end private def select_primary_mode(options) possible_primary_modes = { encrypt: options[:encrypt], decrypt: options[:decrypt], plain: options[:plain] } primary_mode = possible_primary_modes.select {|k,v| v == true } # validation has already happened, we can access modes safely primary_mode.keys.first end def secret_adapter MuchKeys::Secret end end end