require 'hosts' require 'sct/command_interface' module Sct class HostfileCommand IS_PUBLIC_COMMAND = true SYNTAX = 'sct hostfile' SUMMARY = 'adds the ingress url to the users hostfile' DESCRIPTION = "" EXAMPLE = "sct hostfile" EXAMPLE_DESCRIPTION = "" OPTIONS = [] def self.options end def execute(args, options) return puts "SCT has not been initialized. Run 'sct init' first.".red unless Sct::Config.exists return puts "This command needs to be run with sudo.".red unless Sct::Helpers.isSudo return unless Sct::Helpers.ingressAddress ingressAddress = Sct::Helpers.ingressAddress if options.path hosts_paths = [options.path] else hosts_paths = ["/etc/hosts"] if Sct::Helpers.operatingSystem == Sct::Helpers::WINDOWS hosts_paths << "/mnt/c/Windows/System32/drivers/etc/hosts" end end hosts_paths.each do |hosts_path| hosts = Hosts::File.read(hosts_path) if ([ingressAddress].any? { |ip| hosts.to_s =~ /#{ip}/ }) puts "Skipped patching #{hosts_path} (already up to date)".green else validate_if_exist(hosts) add_entry(ingressAddress, hosts) hosts.write puts "Patched #{hosts_path} with #{ingressAddress}".green end end end def add_entry(url, hosts) spend = Hosts::Entry.new( url, 'spend.cloud.local', :comment => 'The spend cloud ingress url' ) mail = Hosts::Entry.new( url, 'mail.spend.cloud.local', :comment => 'The spend cloud mail url' ) config = Hosts::Entry.new( url, 'config.spend.cloud.local', :comment => 'The spend cloud config url' ) spend_cloud = Hosts::Entry.new( url, 'spend-cloud.spend.cloud.local', :comment => 'The spend cloud web app url' ) docs = Hosts::Entry.new( url, 'docs.spend.cloud.local', :comment => 'The spend cloud documentation url' ) hosts.elements << spend hosts.elements << mail hosts.elements << config hosts.elements << spend_cloud hosts.elements << docs end def validate_if_exist(array) rejectArray = Array.new array.to_s.each_line.with_index do |line, index| if (line =~ /(?:spend\.cloud\.local)./) rejectArray.push(index) end end array.elements.delete_if.each_with_index { |value, index| rejectArray.include? index } end implements CommandInterface end end