#!/usr/bin/env perl
use strict;
use warnings;

use POSIX qw(uname);
use MYDan;
use File::Basename;
use MYDan::Util::OptConf;
use Digest::MD5;
use MYDan::Bootstrap

$| ++;

$MYDan::Util::OptConf::THIS = 'bootstrap';

=head1 SYNOPSIS

 $0 --install
 $0 --uninstall  

 $0 --stop
 $0 --start
 $0 --restart

=cut

my $option = MYDan::Util::OptConf->load();
my %o = $option->get( qw( install uninstall start stop restart ) )->dump();

$option->assert() unless grep{ $o{$_} }qw( install uninstall start stop restart );

( $o{stop}, $o{start} ) = ( 1, 1 ) if $o{restart};

my $bootstrap = MYDan::Bootstrap->new( %o );

my $uuid = substr Digest::MD5->new->add( $ENV{MYDanPATH} = $MYDan::PATH )->hexdigest, 0, 7;

my $os = ( uname() )[0];
my $user = `id -un`;
chomp $user if $user;


if( $o{install} )
{
    my $rs = "$MYDan::PATH/var/ReservedSpace";
    unless( -d $rs )
    {
        die "mkdir fail:$!" if system "mkdir -p '$rs'";
    }
    map{ 
        unless( -f "$rs/$_" )
        {
            die "make ReservedSpace fail:$!" if system "echo ReservedSpace > '$rs/$_'";
        }
    
    } 1..100;

    if( $os =~ /CYGWIN/ )
    {
        die "user undef" unless $user;
        my $path = "/var/cron/tabs/$user";
        die "sed fail: $!" if system "sed -i '/mydan_bootstrap_cron_$uuid/d' $path";
        die "install fail:$!" if system "echo '\@reboot $MYDan::PATH/dan/bootstrap/bin/bootstrap --start > /dev/null 2>&1' >> $path"
    }
    else
    {
        die "insall fail:$!" if system "echo '\@reboot root $MYDan::PATH/dan/bootstrap/bin/bootstrap --start >/dev/null 2>&1' > /etc/cron.d/mydan_bootstrap_cron_$uuid";
    }
    exit;
}
if( $o{uninstall} )
{
    if( $os =~ /CYGWIN/ )
    {
        die "user undef" unless $user;
        die "sed fail: $!" if system "sed -i '/mydan_bootstrap_cron_$uuid/d' '/var/cron/tabs/$user'";
    }
    else
    {
        unlink "/etc/cron.d/mydan_bootstrap_cron_$uuid";
    }
    die "stop fail: $!" if system "killall $uuid.mydan.bootstrap.master";
    exit;
}

if( $o{stop} )
{
    system "killall $uuid.mydan.bootstrap.master";
    map{ chomp }my @x = `ps -ef|grep $uuid.mydan.bootstrap.maste[r]`;
    die sprintf( "kill fail: %s\n", join ',', @x ) if @x;
}
if( $o{start} )
{
    exit 0 if fork;
    $0 = "$uuid.mydan.bootstrap.master";
    $bootstrap->run();
}
