#!/usr/bin/perl -w

# Generate a keyfile for archives encryption

my $keyfile = '/etc/BackupPC/archive.key';

if (! -e $keyfile){
    use MIME::Base64 qw(encode_base64);

    my $key = "not set due to error";
    if ( open( RANDOM, "/dev/urandom" ) ){   
        my $buf;
        # 57 bytes is a full line of Base64 coding, and contains
        # 456 bits of randomness - given a perfectly random /dev/random
        if ( read( RANDOM, $buf, 57 ) != 57 )
        {   
            warn("Short read from /dev/random: $!");
        }
        else
        {   
            $key = encode_base64($buf);
            chomp $key;
        }
        close RANDOM;
    }
    else
    {   
        warn "Could not open /dev/urandom: $!";
    }
    open( KEYFILE, ">$keyfile") || warn "Could not open $keyfile: $!";
    print KEYFILE $key;
    close KEYFILE;
}
