This repository has been archived by the owner on Mar 30, 2020. It is now read-only.
/
ghost
executable file
·107 lines (102 loc) · 2.58 KB
/
ghost
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env ruby
#
# Created by Bodaniel Jeanes on 2008-8-19.
# Copyright (c) 2008. All rights reserved.
begin
require 'rubygems'
rescue LoadError
# no rubygems to load, so we fail silently
end
require 'ghost'
def help_text(exit_code = 0)
script_name = File.basename $0
puts """USAGE: #{script_name} add <hostname> [<ip=127.0.1.1>]
#{script_name} modify <hostname> <ip>
#{script_name} delete <hostname>
#{script_name} list
#{script_name} empty
#{script_name} export
#{script_name} import <file>
"""
exit(exit_code)
end
if ARGV.size.zero? || ['-h', '--help', 'help'].include?(ARGV.first)
help_text
else
case ARGV[0]
when 'add'
if [2,3].include?(ARGV.size)
begin
ARGV.shift
host = Host.add(*ARGV)
puts " [Adding] #{host.name} -> #{host.ip}"
exit 0
rescue
$stderr.puts "Cannot overwrite an existing entry. Use the modify subcommand"
exit 3
end
else
$stderr.puts "The add subcommand requires at least a hostname.\n\n"
help_text 2
end
when 'modify'
if ARGV.size == 3
ARGV.shift
ARGV << true
host = Host.add(*ARGV)
puts " [Modifying] #{host.name} -> #{host.ip}"
exit 0
else
$stderr.puts "The modify subcommand requires a hostname and an IP.\n\n"
help_text 4
end
when 'delete', 'del', 'remove', 'rm'
if ARGV.size == 2
Host.delete(ARGV[1])
puts " [Deleting] #{ARGV[1]}"
exit 0
else
$stderr.puts "The delete subcommand requires a hostname.\n\n"
help_text 2
end
when 'list'
hosts = Host.list
pad = hosts.max{|a,b| a.to_s.length <=> b.to_s.length }.to_s.length
puts "Listing #{hosts.size} host(s):"
hosts.each do |host|
puts "#{host.name.rjust(pad+2)} -> #{host.ip}"
end
exit 0
when 'empty'
print " [Emptying] "
Host.empty!
puts "Done."
exit 0
when 'export'
hosts = Host.list
hosts.each do |host|
puts "#{host.name} #{host.ip}"
end
exit 0
when 'import'
if ARGV.size == 2
begin
File.foreach(ARGV[1]) do |line|
host_infos = line.strip.split(' ', 2)
host = Host.add(*host_infos)
puts " [Adding] #{host.name} -> #{host.ip}"
end
exit 0
rescue
$stderr.puts "Cannot import. A problem occured while opening the import file."
exit 5
end
else
$stderr.puts "The import command requires an input file.\n\n"
help_text 6
end
else
$stderr.puts "Invalid option: #{ARGV[0]}"
help_text 1
end
end