Sha256: 7388edd6885b5f44f1828acbc967f1bddbde180fc8689cbd773bc420d4ba8933

Contents?: true

Size: 1.89 KB

Versions: 4

Compression:

Stored size: 1.89 KB

Contents

require "tmpdir"
require "shellwords"

module Rtprov
  class Router
    ATTRIBUTES = %w(host user password administrator_password anonymous_password variables).map(&:freeze).freeze

    attr_reader :name, *ATTRIBUTES

    def self.edit(name)
      encrypted_file = "routers/#{name}.yml.enc"
      decrypted = if File.exist?(encrypted_file)
        Encryption.decrypt(File.read(encrypted_file))
      else
        <<~YAML
          host: 127.0.0.1
          user: admin
          password: opensesame
          administrator_password: opensesame
          anonymous_password: anonymous_password
          variables: {}
        YAML
      end

      Dir.mktmpdir do |dir|
        temp = "#{dir}/#{name}.yml"
        File.write(temp, decrypted)

        if system("#{editor} #{temp.shellescape}", out: $stdout, err: $stderr)
          encrypted = Encryption.encrypt(File.read(temp))
          File.write(encrypted_file, encrypted)
          warn "Saved to #{encrypted_file}"
        else
          warn "Not saved"
        end
      end
    end

    def self.editor
      return ENV["RTPROV_EDITOR"] if ENV["RTPROV_EDITOR"]

      # rubocop: disable Lint/HandleExceptions
      begin
        o, _e, s = Open3.capture3("git config core.editor")
        return o.strip if s.success?
      rescue Errno::ENOENT
      end
      # rubocop: enable Lint/HandleExceptions

      ENV["EDITOR"]
    end

    def self.decrypt(name)
      Encryption.decrypt(File.read("routers/#{name}.yml.enc"))
    end

    def self.names
      Dir["routers/*.yml.enc"].map {|path|
        File.basename(path).gsub(/\.yml\.enc\z/, "")
      }.sort
    end

    def self.load(name)
      new(name, YAML.safe_load(decrypt(name)))
    end

    def initialize(name, attributes)
      @name = name

      attributes.each do |k, v|
        ATTRIBUTES.include?(k) || raise("Unknown attribute found `#{k}`")
        instance_variable_set "@#{k}", v
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rtprov-0.1.3 lib/rtprov/router.rb
rtprov-0.1.2 lib/rtprov/router.rb
rtprov-0.1.1 lib/rtprov/router.rb
rtprov-0.1.0 lib/rtprov/router.rb