package Platform;

# no warnings qw( uninitialized );

print "loading BS_unix\n" if( $BigSister::common::dl );

require Exporter;
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);

@ISA = qw( Exporter );

@EXPORT = qw( bsconnect bsalarm );


$Platform::has_fork = 1;


sub bsalarm {
    my( $time ) = @_;

    return alarm( $time );
}


sub bsconnect {
    my( $socket, $addr ) = @_;
    
    return connect( $socket, $addr );
}


sub socknonblock {
    my( $socket ) = @_;

    $flags = fcntl($socket, F_GETFL, 0) || return 0;
    return( fcntl($socket, F_SETFL, $flags | O_NONBLOCK) );
}


sub bswait {
    wait;
}


sub bswait_nohang {
    require POSIX;
    my $pid = waitpid( -1, &POSIX::WNOHANG );
    return( $pid?$pid:-1 );
}


sub strftime {
    require POSIX;
    return( POSIX::strftime( $_[0], gmtime($_[1]) ) );
}


sub hostname {
    my( $fqdn ) = @_;

    my $hostname;
    eval {
	require Sys::Hostname;
	$hostname = Sys::Hostname::hostname();
    };
    $hostname || ($hostname = $ENV{"HOST"});
    $hostname || chomp( $hostname = `/bin/hostname` );
    $hostname =~ s/\..*// unless( $fqdn );
    # take host name as it is
    # $hostname =~ tr/A-Z/a-z/;
    return( $hostname );
}


sub override_root {
    return undef;
}



sub replace {
    my( $file, $newfile ) = @_;

    return( rename( $file, $newfile ) );
}


sub system {
    my( @args ) = @_;

    return( system( @args ) );
}


sub filepath {
    my( $name ) = @_;

    return $name;
}


sub background_process {
    my( $path, $cmdline ) = @_;
    my( $generator );

    print "starting in background: $path: $cmdline\n" if( $BigSister::common::dl>1 );
    my $pid = fork();
    return($pid) if( $pid );
    unless( defined $pid ) {
        BigSister::common::log( "err", "cannot fork" );
	return undef;
    }
    exec( $cmdline );
    exit(1);
}



sub mergepath {
    my( $add, $atend ) = @_;

    if( $atend ) {
	$ENV{"PATH"} .= ":$add";
    } else {
	$ENV{"PATH"} = $ENV{"PATH"}.":$add";
    }
}

1;
