2019-10-20 18:05:31 +02:00
|
|
|
require "file_utils"
|
2019-10-25 13:10:20 +02:00
|
|
|
require "option_parser"
|
|
|
|
|
2019-10-20 18:05:31 +02:00
|
|
|
require "./config.cr"
|
|
|
|
|
|
|
|
START_PORT = 49152
|
|
|
|
PORTS_CACHE_DIRECTORY = "#{CACHE_DIRECTORY}/ports/"
|
|
|
|
|
2019-10-25 13:10:20 +02:00
|
|
|
service = ""
|
|
|
|
wanted_default_port : String? = nil
|
|
|
|
|
|
|
|
parser = OptionParser.parse do |parser|
|
|
|
|
parser.banner = "usage: get-post <id> [default-port] [options]\n" +
|
|
|
|
"options:\n"
|
|
|
|
|
|
|
|
parser.on "-h", "--help", "Prints this help message." do
|
|
|
|
puts parser
|
|
|
|
exit 0
|
|
|
|
end
|
|
|
|
|
|
|
|
parser.unknown_args do |arg|
|
|
|
|
if arg.size < 1 || arg.size > 2
|
|
|
|
puts parser
|
|
|
|
exit 1
|
|
|
|
end
|
|
|
|
|
|
|
|
service = arg[0]
|
|
|
|
wanted_default_port = arg[1]?
|
|
|
|
end
|
|
|
|
end
|
2019-10-20 18:05:31 +02:00
|
|
|
|
2019-10-24 15:48:03 +02:00
|
|
|
service_port_file = "#{PORTS_CACHE_DIRECTORY}/#{service.gsub /\//, ":"}"
|
2019-10-20 18:05:31 +02:00
|
|
|
|
|
|
|
begin
|
|
|
|
if File.exists? service_port_file
|
|
|
|
puts File.read service_port_file
|
|
|
|
exit 0
|
|
|
|
end
|
|
|
|
|
|
|
|
FileUtils.mkdir_p PORTS_CACHE_DIRECTORY
|
|
|
|
|
|
|
|
used_ports = Dir.children(PORTS_CACHE_DIRECTORY)
|
|
|
|
.map { |x| "#{PORTS_CACHE_DIRECTORY}/#{x}" }
|
|
|
|
.map { |x| File.read(x).to_i }
|
|
|
|
.sort
|
|
|
|
|
|
|
|
port = START_PORT
|
|
|
|
if wanted_default_port && ! used_ports.any? &.==(wanted_default_port)
|
|
|
|
port = wanted_default_port
|
|
|
|
else
|
|
|
|
while used_ports.any? &.==(port)
|
|
|
|
port = port + 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
File.write service_port_file, port
|
|
|
|
|
|
|
|
puts port
|
|
|
|
rescue e
|
|
|
|
STDERR.puts "error: #{e.message}"
|
|
|
|
exit 1
|
|
|
|
end
|
|
|
|
|