Cleanup and proper licensing blurb
[hostuuid.git] / hostuuid.pl
blob3489059c071a4f26f107a8797a1ce337e661f9ff
1 #!/usr/bin/perl
3 #This program is free software: you can redistribute it and/or modify
4 #it under the terms of the GNU General Public License as published by
5 #the Free Software Foundation, either version 3 of the License, or
6 #(at your option) any later version.
8 #This program is distributed in the hope that it will be useful,
9 #but WITHOUT ANY WARRANTY; without even the implied warranty of
10 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 #GNU General Public License for more details.
13 #You should have received a copy of the GNU General Public License
14 #along with this program. If not, see <http://www.gnu.org/licenses/>.
16 # Written by Richard Hartmann in 2009, feel free to email
17 # richih.mailinglist@gmail.com with questions.
20 use strict;
21 use warnings;
23 use UUID::Tiny;
24 use Getopt::Long qw(:config no_ignore_case bundling);
25 use File::Basename;
27 my $version = '1.0';
28 my $program = basename($0);
30 my $file = '/etc/hostuuid';
31 my $print_version;
32 my $print_help;
33 my $create_uuid = 0;
35 GetOptions (
36 'file|f=s' => \$file,
37 'help|h|?' => \$print_help,
38 'version|v' => \$print_version,
39 'create|c' => \$create_uuid,
42 sub print_version() {
43 print <<VERSION;
44 $program: version $version
46 This program is released under GPLv3
47 Written by Richard Hartmann for Debian and Grml
48 VERSION
49 exit 0;
52 sub print_help() {
53 print <<HELP;
54 Help for $program:
56 -h, -?, --help : print this help
57 -v, --version : print version
58 -f, --file : file to read from/write to. Defaults to /etc/hostuuid
59 -c, --create : create & save UUID
60 HELP
61 exit 0;
64 sub create_uuid() {
65 my $uuid = find_hostuuid();
66 if ($uuid) {
67 print STDERR "$program: Found UUID '$uuid' in '$file'. Aborting!\n";
68 exit 101;
69 } else {
70 open (F, ">", "$file") or die "$program: Could not open file: '$file'\: $!\n";
71 $uuid = create_UUID_as_string(UUID_V4);
72 print "$program\: Stored UUID '$uuid' in file '$file'\n";
73 print F "$uuid\n";
74 close (F);
75 exit 0;
79 sub find_hostuuid() {
80 # if ($create_uuid) {return 0 unless -e $file;}
81 return 0 unless ((-e $file && $create_uuid) || !$create_uuid);
82 open (F, "<", "$file") or die "$program: Could not open file: '$file'\: $!\n";
83 while (<F>) {
84 if (/([0-9a-z]{8}-([0-9a-z]{4}-){3}[0-9a-z]{12})/i) {
85 close (F);
86 return $1;
91 sub main() {
92 print "\n\nIf anyone knows how to die() when there is no value for -f, tell me!\n\n";
93 chomp $file;
94 print_version() if $print_version;
95 print_help() if $print_help;
96 create_uuid() if $create_uuid;
98 my $uuid = find_hostuuid();
99 if ($uuid) {
100 print "$uuid\n";
101 exit 0;
102 } else {
103 print STDERR "$program: Could not find UUID in '$file'\n";
104 exit 100;
108 main();