# Copyright (c) 2004  Joshua Hoblitt
#
# $Id: Util.pm,v 1.6 2007-05-05 02:54:52 jhoblitt Exp $

package Nebulous::Util;

use strict;
use warnings FATAL => qw( all );

our $VERSION = '0.01';

use base qw( Exporter );

use File::ExtAttr qw( setfattr );
use Log::Log4perl qw( :levels );
use URI::file;
use URI;

my @symbols = qw(
    %LEVELS
    _nuke_file
    _get_file_path
    _get_filehandle
    _open_uri
    _create_empty_file
);

our @EXPORT_OK      = @symbols;
our %EXPORT_TAGS    = ( standard => [ @symbols ] );

our %LEVELS = (
    off     => $OFF,
    fatal   => $FATAL,
    error   => $ERROR,
    warn    => $WARN,
    info    => $INFO,
    debug   => $DEBUG,
    all     => $ALL,
);

sub _nuke_file {
    my $path = shift;

    die "can't unlink file $path: it's a directory" 
        if -d $path;
    die "can't unlink file $path: it doesn't exist"
        unless -e $path;
    unlink $path or die "can't unlink file $path: $!";

    return 1;
}

sub _get_file_path {
    my $uri = shift;

    my $path = URI->new( $uri )->path;

    return $path;
}

sub _get_filehandle {
    my ( $path, $flags ) = @_;

    die "can't open file $path: file doesn't exist" 
        unless -e $path;
    CORE::open( my $fh, $flags, $path )
        or die "can't open file $path: $!";

    return $fh;
}

sub _open_uri {
    my ( $uri , $flags ) = @_;

    $uri = URI->new("$uri");

    my $fh = _get_filehandle($uri->file, $flags);

    return $fh;
}

sub _create_empty_file
{
    my ($path, $key) = @_;

    # perl's open() can't do an O_CREAT | O_EXCL
    die "file $path already exists" if (-e $path);

    my $fh;
    die "can not open $path: $!"
        unless (open($fh, '>', $path));

    die "can not close $path: $!"
        unless (close($fh));

    die "can not chmod $path: $!"
        unless (chmod 0664, $path);

    die "can not set xattr on $path: $!"
        unless (setfattr($path, 'user.nebulous_key', $key));

    return $path;
}

1;

__END__
