| 1 | package Mojo::Command::Generate::InitScript::Freebsd; | ||
| 2 | |||
| 3 | use warnings; | ||
| 4 | use strict; | ||
| 5 | use File::Spec; | ||
| 6 | |||
| 7 | #use base 'Mojo::Command::Generate::InitScript::Base'; | ||
| 8 | use base 'Mojo::Command'; | ||
| 9 | use Getopt::Long 'GetOptions'; | ||
| 10 | use File::Spec; | ||
| 11 | use IO::File; | ||
| 12 | |||
| 13 | __PACKAGE__->attr(usage => <<"EOF"); | ||
| 14 | FreeBSD related initscript options: | ||
| 15 | --before <applist> Defines services which | ||
| 16 | should start after this initscript | ||
| 17 | for example: --before nginx | ||
| 18 | --requre <applist> Defines services which | ||
| 19 | should be started before this initscript | ||
| 20 | for example: --requre postgresql | ||
| 21 | EOF | ||
| 22 | |||
| 23 | sub run | ||
| 24 | { | ||
| 25 | my ( $self, $opt ) = @_; | ||
| 26 | |||
| 27 | $opt->{'before'} = []; | ||
| 28 | $opt->{'require'} = []; | ||
| 29 | |||
| 30 | GetOptions($opt, | ||
| 31 | 'before=s{,}', 'require=s{,}', | ||
| 32 | ); | ||
| 33 | |||
| 34 | my $rc_file = $opt->{'deploy'} | ||
| 35 | ? '/usr/local/etc/rc.d/'. $opt->{'name'} | ||
| 36 | : File::Spec->join($opt->{'output'}, $opt->{'name'}); | ||
| 37 | $self->render_to_file( 'initscript', $rc_file, $opt ); | ||
| 38 | $self->chmod_file( $rc_file, 0755 ); | ||
| 39 | |||
| 40 | # update /etc/rc.conf | ||
| 41 | $self->update_rc_conf( $opt->{'name'} ) if $opt->{'deploy'}; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub update_rc_conf | ||
| 45 | { | ||
| 46 | my ( $self, $name ) = @_; | ||
| 47 | |||
| 48 | my $fh = IO::File->new(); | ||
| 49 | $fh->open('/etc/rc.conf', '+<') or die qq{Can't open /etc/rc.conf\n}; | ||
| 50 | my $current_pos = 0; | ||
| 51 | my @lines = (); | ||
| 52 | my $read_lines = 0; | ||
| 53 | my $update_from_pos = undef; | ||
| 54 | my $already_done = 0; | ||
| 55 | while ( my $line = $fh->getline ) | ||
| 56 | { | ||
| 57 | chomp $line; | ||
| 58 | if ( $read_lines ) | ||
| 59 | { | ||
| 60 | push @lines, $line; | ||
| 61 | next; | ||
| 62 | } | ||
| 63 | if ( $line =~ m/^\Q$name\E_enable="(.*?)"$/i ) | ||
| 64 | { | ||
| 65 | if ( $1 =~ /^yes$/i ) | ||
| 66 | { | ||
| 67 | $already_done = 1; | ||
| 68 | last; | ||
| 69 | } | ||
| 70 | $update_from_pos = $current_pos; | ||
| 71 | $read_lines = 1; | ||
| 72 | } | ||
| 73 | $current_pos = $fh->tell; | ||
| 74 | } | ||
| 75 | |||
| 76 | if ( ! $already_done ) | ||
| 77 | { | ||
| 78 | if ( defined $update_from_pos ) | ||
| 79 | { | ||
| 80 | $fh->seek( $update_from_pos, 0 ); | ||
| 81 | } | ||
| 82 | $fh->print("\n") if $fh->eof; | ||
| 83 | $fh->print($name, '_enable="YES"', "\n"); | ||
| 84 | if ( @lines ) | ||
| 85 | { | ||
| 86 | $fh->print( join("\n", @lines) ); | ||
| 87 | } | ||
| 88 | $fh->truncate( $fh->tell ); | ||
| 89 | } | ||
| 90 | close $fh; | ||
| 91 | } | ||
| 92 | |||
| 93 | 1; | ||
| 94 | __DATA__ |