
package JK::Lib::Misc;

use strict;
use Sys::Syslog;

my @EXPORT = qw/debug delaydie
                getpid get_random
                mysleep
                slowdie
                verbose
               /;
                
sub mysleep {
    my ($total,$interval) = @_;

    my $nextrun = ( time() + $total );
    while( time() < $nextrun ){
        debug( "* sleeping $interval" );
        sleep $interval;
    }
}

sub get_random {
    my $len = shift || die "specify random length\n";

    my ($random,$buf,$x);
    open(my $ur, '/dev/urandom') || die "cannot open /dev/urandom: $!\n";
    my @set = ('A'..'Z', 'a'..'z', '0'..'9', '_', '.');
    for(1..${len}){
        sysread($ur, $buf, 1);
        my $v = ord($buf);
        $x ^= ($v & ~63) >> (rand(7)+1);
        $random .= $set[ ($x ^ ord($buf)) & 63 ];
    }
    close $ur;

    return $random;
}

sub verbose {
    my $msg = join('', @_);

    warn "$msg\n" if $::opt{f};
    syslog( 'info', $msg );
}

sub debug {
    verbose(@_) if $::opt{D};
}

sub delaydie {
    my $delay = shift || slowdie( "delaydie: no delay" );

    verbose( "delay request for $delay seconds." );
    undef $::ua;
    for my $x (keys %::dbh){
        $::dbh{$x}->disconnect;
    }
    $::dbh->disconnect if $::dbh;
    sleep $delay;
    exit;
}

sub slowdie {
    verbose(@_);   
    sleep 5;
    exit 1;
}

sub getpid {
    my $name = shift || slowdie( "getpid: no name" );

    my $pid;
    open(my $ps, '-|', 'ps', 'ax') || die "cannot pipe to ps: $!\n";
    while(<$ps>){
        if( /^\s*(\d+)\s+\S+\s+\S+\s+\S+\s+.*${name}/ ){
            $pid = $1;
            last;
        }
    }
    close $ps;

    return $pid;
}

sub import {
    my $pkg = shift;
    my $caller = caller;

    for my $f ( @EXPORT ){
        no strict;
        *{$caller . '::' . $f} = $pkg->can($f);
    }
}

1;
