bin/vhost

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
# frozen_string_literal: true

require 'rubygems'
require 'bundler'
Bundler.setup :default

require 'gli'
require 'phut'

module Phut
  class VhostDaemon
    # /bin/vhost command
    # rubocop:disable BlockLength
    module App
      extend GLI::App

      version Phut::VERSION

      desc 'Runs a vhost process'
      command :run do |c|
        desc 'Host name'
        c.flag %i[n name]
        desc 'Network interface'
        c.flag %i[I interface]
        desc 'IP address'
        c.flag %i[i ip_address]
        desc 'MAC address'
        c.flag %i[m mac_address]
        c.desc 'ARP entries'
        c.flag %i[a arp_entries], negatable: false
        c.desc 'Promisc mode'
        c.switch %i[p promisc], negatable: false

        c.desc 'Location to put pid files'
        c.flag %i[P pid_dir], default_value: Phut.pid_dir
        c.desc 'Location to put log files'
        c.flag %i[L log_dir], default_value: Phut.log_dir
        c.desc 'Location to put socket files'
        c.flag %i[S socket_dir], default_value: Phut.socket_dir

        c.action do |_global_opts, opts, _args|
          raise '--name option is mandatory' if opts[:name].nil?
          raise '--ip_address option is mandatory' if opts[:ip_address].nil?
          raise '--mac_address option is mandatory' if opts[:mac_address].nil?
          opts[:arp_table] =
            (opts[:arp_entries] || '').split(',').
            each_with_object({}) do |each, table|
              ip_address, mac_address = each.split('/')
              table[ip_address] = mac_address
            end
          VhostDaemon.new(opts).run
        end
      end

      desc 'Terminates a vhost process'
      command :stop do |c|
        desc 'Host name'
        c.flag %i[n name]
        c.desc 'Location to put socket files'
        c.flag %i[S socket_dir], default_value: Phut.socket_dir

        c.action do |_global_opts, opts, _args|
          raise '--name option is mandatory' if opts[:name].nil?
          begin
            VhostDaemon.process(opts[:name], opts[:socket_dir]).kill
          rescue DRb::DRbConnError
            true # OK
          end
        end
      end

      desc 'Sends UDP packets to destination host'
      command :send_packets do |c|
        desc 'Source host name'
        c.flag %i[s source]

        c.action do |_global_opts, opts, _args|
          raise '--source option is mandatory' if opts[:source].nil?
          VhostDaemon.process(opts[:source], opts[:socket_dir]).
            send_packets
        end
      end

      default_command :help

      exit run(ARGV)
    end
    # rubocop:enable BlockLength
  end
end