#!/usr/bin/env ruby
require 'veil'
require 'json'
require 'optparse'

options = { debug: false }

OptionParser.new do |opts|
  opts.banner = <<EOF
Usage: veil-ingest-secret [options] [SECTION.]NAME

Manually add secrets to a secrets provider. This is configured via environment
variables:

  * PROVIDER=chef-secrets-file       Secrets provider to use
  * PROVIDER_CONFIG                  Configuration for the secrets provider (JSON)
                                     - defaults differ according to providers

  Options:
EOF

  opts.on("--[no-]debug", "Emit diagnostic messages.  This will print secrets. Do not use this in production") do |d|
    options[:debug] = d
  end
end.parse!

config = JSON.parse(ENV['PROVIDER_CONFIG'] || "{}", symbolize_names: true)
config[:provider] = ENV['PROVIDER'] || 'chef-secrets-file'
STDERR.puts "Using config #{config}" if options[:debug]

veil = Veil::CredentialCollection.from_config(config)

secret = ARGV.first
veil_args = secret.split(".")
STDERR.puts "veil_args = #{veil_args}" if options[:debug]

STDERR.puts "Reading from stdin" if options[:debug]
value = STDIN.read.chomp

veil.add(*veil_args, value: value, frozen: true, force: true)
veil.save
